1.普通使用
在原生html文件中使用
<input type="file" @change="handleFileChange">
const handleFileChange = (e) => {
console.log(e.target.files)
const file = e.target.files[0];
// 处理文件
}
2.element-plus组件库中使用
基础用法
<el-upload
action="https://your-upload-api.com"
:on-success="handleSuccess"
:on-error="handleError"
>
<el-button type="primary">点击上传</el-button>
</el-upload>
const handleSuccess = (response, file, fileList) => {
console.log('上传成功', response);
}
const handleError = (error, file, fileList) => {
console.error('上传失败', error);
}
使用时action地址为实际可用的字段。
常用属性
属性 | 说明 | 类型 | 默认值 |
---|---|---|---|
action | 上传地址 | string | - |
multiple | 是否支持多选 | boolean | false |
limit | 最大上传数量 | number | - |
accept | 接受的文件类型 | string | - |
drag | 是否启用拖拽 | boolean | false |
auto-upload | 是否自动上传 | boolean | true |
自定义上传
<!-- 自定义上传 -->
<el-upload
:http-request="customRequest"
:show-file-list="false"
>
<el-button type="primary">点击上传</el-button>
</el-upload>
// 自定义上传逻辑
const customRequest = async (options) => {
// 参数解构
const { file, onProgress, onSuccess, onError } = options;
// 上传文件对象 进度回调函数用于更新上传进度 成功回调函数 失败回调函数
try {
const formData = new FormData();
//创建formdata对象,浏览器提供的用于表单数据提交的api
formData.append('file', file);//将文件添加到表单数据中,字段名为file
// 添加其他字段
formData.append('uploadTime', new Date().toISOString());
const res = await axios.post('/api/upload', formData, {
headers: {
'Authorization': 'Bearer your_token_here',
'Content-Type': 'multipart/form-data'
},
onUploadProgress: (e) => {
onProgress({ percent: (e.loaded / e.total) * 100 });
}
});
onSuccess('上传成功',res.data);
} catch (err) {
onError('上传失败',err);
}
}