1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > Vue Element-ui上传图片踩坑

Vue Element-ui上传图片踩坑

时间:2023-01-04 12:31:25

相关推荐

Vue Element-ui上传图片踩坑

Element-ui上传图片踩坑

使用Element-ui组件上传图片时,使用自带的action发起上传请求时碰到400错误

错误代码

<el-uploadclass="upload-demo"action="http://localhost:8080/create/uploadAvatar":on-preview="handlePreview":on-remove="handleRemove":before-remove="beforeRemove":limit="1":on-exceed="handleExceed":file-list="fileList"list-type="picture":before-upload="beforeUpload" //上传之前执行:data="dataForm" //上传时额外带的参数,注意是额外name="avatar" //一看是不知道这个就是文件参数名称:headers="headers"><el-button size="small" type="primary">点击上传</el-button></el-upload>

methods: {handleRemove(file, fileList) {console.log(file, fileList);},handlePreview(file) {this.$message.warning(`,,,,,`);console.log(file);},handleExceed(files, fileList) {this.$message.warning(`最多选择一张图片`);},beforeRemove(file, fileList) {return this.$confirm(`确定移除 ${file.name }?`);},beforeUpload(file) {//全部是多余操作,根本不用写这个函数/*this.headers = {"Content-Type": 'multipart/form-data'} this.avatarParamBody = {avatar: file,};console.log(this.avatarParamBody);console.log(this.headers);*/}

1.上传时,服务端没有接受到对应名称的参数。

弄了很久都没有解决,我就想着怎么就接受不到avatar作为文件参数名。

后来查了很多帖子才知道,有一个name属性对应的就是参数名,直接在组件里面写个name=“avatar”就可以,完全不用自己加参数。

2.第一次上传成功,第二次报错

原来这个发起上传请求会自动给加上清求头"Content-Type": 'multipart/form-data'

我在beforeUpload中加入了请求头,第一次没问题,但第二次就写了连个Content-Type参数,导致后端报错。

这么一来before-upload的函数就是多余的!!!除非有需要

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。