前端实现文件上传功能

158 阅读1分钟

前端实现文件上传

  1. 在页面上使用el-upload组件,在组件方法里写一个on-change回调函数
<el-upload ref="uploadRef1" :on-change="(file: any) => upLoadFiles(file, 'Procedure_Image')"
                        :auto-upload="false" :limit="1" :show-file-list="true" accept=".ppt, .pptx"
                        :on-exceed="(file: any) => handleExceed(file, 1)">
                        <div ref="uploadFileIcon">
                            <el-button color="#276DEA" type="primary">
                                <img :src="uploadFile" alt="">
                                <span style="margin-left: 5px;">上传文件</span>
                            </el-button>
                        </div>
                    </el-upload>
  1. on-change回调函数中会携带file参数,使用const formData = new FormData();创建表单。
  2. 往表单中添加对应的值,
formData.append("files", file.raw);
formData.append("file_type", type);
formData.append("tag_name", "default"); // TODO: 标签获取
formData.append("uploader", mainStore.userId);
  1. 使用axios发送请求给后端, apiChat.uploadTemplateFiles(formData).then((res: any) => { ElMessage({ message: "上传成功", type: 'success', }) });
uploadTemplateFiles(params: any) {
    const url = "/api/upload/template_files";
    return axios.post(url, params, {});
}