需求:表单中直接使用input进行文件上传,并直接传到后端表单接口
出现的问题:
1.全局接口配置的请求头是application/json,要传formData需要修改请求头(不可能,绝对不可能)
2.后端不单独对文件进行储存,因此无法使用独立封装的上传组件
解决方案:file转base64编码,然后通过JSON格式发送给服务器。
代码实现:
const fileInput = document.querySelector("#file"); const file = fileInput.files[0]; const reader = new FileReader(); reader.readAsDataURL(file); const that = this; reader.onload = (e) => { params.file = e.target.result; // 转化后的base64字符串 that.fetchSubmit(params); };
动态表单组件里需要补充input的file相关属性内容:
后端解码后乱码问题可参照:
https://www.php.cn/faq/526560.html
标签:const,elementui,表单,file,reader,input,上传 From: https://www.cnblogs.com/nangras/p/18311315