面试题答案
一键面试1. 使用原生 HTML5 文件输入元素实现文件上传到服务器
在 Vue 项目中,可以按以下步骤实现:
- 模板部分:在 Vue 组件的模板中添加
input
元素用于选择文件,并添加一个按钮用于触发上传。
<template>
<div>
<input type="file" @change="handleFileChange" />
<button @click="uploadFile">上传文件</button>
</div>
</template>
- 脚本部分:在 Vue 组件的
script
中编写处理函数。
export default {
data() {
return {
file: null
};
},
methods: {
handleFileChange(e) {
this.file = e.target.files[0];
},
uploadFile() {
const formData = new FormData();
formData.append('file', this.file);
fetch('/api/upload', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
console.log('文件上传成功', data);
})
.catch(error => {
console.error('文件上传失败', error);
});
}
}
};
上述代码中,handleFileChange
方法在用户选择文件后将文件对象存储在 Vue 实例的 file
数据属性中。uploadFile
方法创建一个 FormData
对象,将选择的文件添加到其中,然后使用 fetch
发送 POST 请求到服务器的 /api/upload
接口。
2. 文件上传过程中常见问题及处理方式
文件类型限制
可以在 handleFileChange
方法中添加对文件类型的判断。
handleFileChange(e) {
const allowedTypes = ['image/jpeg', 'image/png', 'application/pdf'];
const file = e.target.files[0];
if (allowedTypes.includes(file.type)) {
this.file = file;
} else {
console.error('不允许的文件类型');
}
}
上述代码定义了一个允许的文件类型数组 allowedTypes
,在选择文件时判断文件的 type
是否在允许的类型数组中。
文件大小限制
同样在 handleFileChange
方法中处理文件大小限制。假设限制文件大小为 5MB(5 * 1024 * 1024 字节)。
handleFileChange(e) {
const maxSize = 5 * 1024 * 1024;
const file = e.target.files[0];
if (file.size <= maxSize) {
this.file = file;
} else {
console.error('文件大小超过限制');
}
}
上述代码通过比较文件的 size
属性与设定的最大大小 maxSize
来判断文件大小是否符合要求。