1. 程式人生 > >vue+elemenui 跨域上傳圖片

vue+elemenui 跨域上傳圖片

.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>

配置檔案: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': ''  
        }
      }
    },