element ui 解决上传图片跨域
近期项目有上传图片功能,项目用的是element UI 搭的vue 框架,在看了官方文档之后,复制代码调式,浏览器一直提示跨域,百度了各种解决方法,都是无效,下面举例百度的方法:
方法一:配置文件:config>index.js
dev: {
// Paths
assetsSubDirectory: "static",
assetsPublicPath: "/",
proxyTable: {
"/api": { //代理后端的接口
target: "*****", // 后端接口
changeOrigin: true,
pathRewrite: {
"/api": ""
}
},
'/img': {//代理请求图片的接口
changeOrigin: true,
secure: false, //https请求需设置此项
target: 'https://abcd.io/data/ocr',
pathRewrite: {
'^/img': ''
}
}
},
此方法对于我来说:无效
方法二:在 el-upload 上面添加 with-credentials=“true”,也是无效
方法三:在el-upload 加上 name ,也是无效
啊,好郁闷啊,后来再仔细看了官方文档,发现有一个属性 http-request,官方文档的解释是:覆盖默认的上传行为,可以自定义上传的实现,就是覆盖action属性,用自己方法覆盖默认上传行为,根据请求返回的code就能处理各种情况,不需要利用默认钩子函数
不说那么多,直接上代码:
template:
<el-upload
class="upload-demo"
action="https://jsonplaceholder.typicode.com/posts/"
:show-file-list="false"
:before-upload="beforeAvatarUpload"
:http-request="uploadFile"
>
<el-button size="small" type="primary">点击上传</el-button>
</el-upload>
script:
methods: {
beforeAvatarUpload(file) {
const isJPG =
file.type === "image/jpg" ||
file.type === "image/jpeg" ||
file.type === "image/png";
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isJPG) {
this.$message.error("仅支持jpg,png格式的图片!");
}
if (!isLt2M) {
this.$message.error("上传图片大小不能超过 2MB!");
}
return isJPG && isLt2M;
},
uploadFile(item) {
let userId = sessionStorage.getItem("userId");
let fileObj = item.file;
const form = new FormData(); // FormData 对象
form.append("file", fileObj); // 文件对象 'upload'是后台接收的参数名
form.append("userId", userId);
this.axios(uploadImge, form, "form")
.then((data) => {
if (data.code == "000000") {
this.$message({
message: "上传成功",
type: "success",
});
this.urlImage = data.content;
}
})
.catch((data) => {
this.$message.error("上传失败,请稍后重试");
});
},
},
这样我就解决了上传图片跨域的问题,各位有更好的解决方法,也欢迎留言讨论
本文章属于原创,转载请注明出处!谢谢