.vue 文件

主要注意这两个:
action 请求的地址。直接请求接口https://… 由于同源策略会出现跨域问题,需要后面配置代理,使本地可以跨域请求接口。
name 表单name值

<temeplate>
	<el-upload
	        class="el-upload--picture-card avatar-uploader"
	        :action="uploadAction"
	        :show-file-list="false"
	        :on-success="handleAvatarSuccess"
	        :before-upload="beforeAvatarUpload"
	        :on-progress="onProgress"
	        name="upfile"
	        :auto-upload="true">
	        <img v-if="imageUrl" :src="imageUrl" class="avatar">
	        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
	</el-upload>
</template>
<script>
  export default ({
    data() {
      return {
        uploadAction: "/img/xxx.json?accountNo=xxx&password=xxx",
        imageUrl: ''
      }
    },
    methods: {   
      beforeAvatarUpload(file) {//请求前
        const isJPG = file.type === 'image/jpg'||file.type === 'image/jpeg'||file.type === 'image/gif'||file.type==='image/bmp'||file.type === 'image/png';
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isJPG) {
          this.$message.error('仅支持jpg,png,bmp,gif格式的图片!');
        }
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M; 
      },
      onProgress(event, file, fileList){//请求中
     },
     handleAvatarSuccess(res, file) {//请求完成
        console.log(res)
        this.imageUrl = URL.createObjectURL(file.raw);
      }      
    },
    mounted() { },
  })
</script>

解决跨域: proxyTable接口代理:
举例:需要请求的接口为:https://abcd.io/data/ocr/xxx.json?accountNo=xxx&password=xxx
代理后:http://localhost:8080/img/xxx.json?accountNo=xxx&password=xxx
onProxyReq: function (proxyReq, req, res) {
//可以通过onProxyReq打印出来看路径的区别
console.log("原路径:" + req.originalUrl, "代理路径:" + req.path)
}

配置文件:config>index.js

dev: {
    // Paths
    assetsSubDirectory: "static",
    assetsPublicPath: "/",
    proxyTable: {
      "/api": { //代理后端的接口
        target: "http://192.168.160.149:8081/", // 后端接口
    	changeOrigin: true,
        pathRewrite: {
          "/api": ""
        }
      },
      '/img': {//代理请求图片的接口
        changeOrigin: true,
        secure: false, //https请求需设置此项
        target: 'https://abcd.io/data/ocr',
        pathRewrite: {
          '^/img': ''  
        }
      }
    },
Logo

前往低代码交流专区

更多推荐