element upload功能官网地址:https://element.eleme.io/#/zh-CN/component/upload
使用这个上传标签的优势在于,你只需要选择选择图片,配置好action这个参数,action这个参数就是你要上传的地址,他就直接上传到服务器了。
我把代码都贴给大家,大家直接看吧,新建个项目,配置好跨域,直接一贴就可以运行。
<template> <div> <el-upload class="avatar-uploader" action="/api/file/upload" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" accept="image/jpeg, image/jpg, image/png" > <img v-if="imageUrl" :src="imageUrl" class="avatar" /> <i v-else class="el-icon-plus avatar-uploader-icon"></i> </el-upload> </div> </template> <script> export default { name: "testuploadimg", data() { return { logoImg: null, imageUrl: "" }; }, methods: { handleAvatarSuccess(res, file) { console.log("res.msg:", res.msg); console.log("file:", file); this.imageUrl = URL.createObjectURL(file.raw); console.log("this.imageUrl:", this.imageUrl); }, beforeAvatarUpload(file) { // const isJPG = file.type === "image/jpeg"; const isLt2M = file.size / 1024 / 1024 < 2; // if (!isJPG) { // this.$message.error("上传头像图片只能是 JPG 格式!"); // } if (!isLt2M) { this.$message.error("上传头像图片大小不能超过 2MB!"); } return isLt2M; }, onChange(image) { console.log("New picture selected!"); if (image) { this.logoImg = this.base64ImgtoFile(image); } else { console.log("FileReader API not supported: use the <form>, Luke!"); } } } }; </script> <style> .avatar-uploader .el-upload { border: 1px dashed #d9d9d9; border-radius: 6px; cursor: pointer; position: relative; overflow: hidden; } .avatar-uploader .el-upload:hover { border-color: #409eff; } .avatar-uploader-icon { font-size: 28px; color: #8c939d; width: 178px; height: 178px; line-height: 178px; text-align: center; } .avatar { width: 178px; height: 178px; display: block; } </style>
一下是我的跨域内容配置:
module.exports = { //放在服务器根目录下面 publicPath:"./", assetsDir:"assets", outputDir:'dist', // 它支持webPack-dev-server的所有选项 devServer: { host: "localhost", port: 8081, // 端口号 https: false, // https:{type:Boolean} open: true, //配置自动启动浏览器 // 配置多个代理 proxy: { "/api": { target: "http://localhost:8081",// 要访问的接口域名 ws: true,// 是否启用websockets changeOrigin: true, //开启代理:在本地会创建一个虚拟服务端,然后发送请求的数据,并同时接收请求的数据,这样服务端和服务端进行数据的交互就不会有跨域问题 pathRewrite: { '^/api': '' //这里理解成用'/api'代替target里面的地址,比如我要调用'http://40.00.100.100:3002/user/add',直接写'/api/user/add'即可 } } ,"/foo": { target: "<other_url>" } } } };
这个是我跨域文件所在路径:
有问题,欢迎留言评论