在前后端分离项目使用upload 组件上传文件时会遇到跨域请求问题,好多是在后端解决的,但是后端用的是spring security,修改影响太大

在前端解决方式是:增加确认上传按钮 手动上传,利用axios请求,话不多说上代码

  • 1.template中代码
   <div v-if="file !== null">
                <span>待上传文件: {{ file.name }}</span>
   </div>
 <Upload action="//jsonplaceholder.typicode.com/posts/"
                            style="display: inline-block;"
                            accept=".xlsx"
                            :max-size="1024"
                            :headers="headers"
                            :before-upload="handleUpload"
                            :on-remove="removeFile"
                            :on-exceeded-size="exceedFile">
                        <Button v-if="file=== null" type="primary" icon="ios-cloud-upload-outline">导入用例</Button>
                    </Upload>
                    <Button  v-if="file !== null" type="primary" @click="uploadFile" >上传文件</Button>
                    <Button  v-if="file !== null" type="primary" @click="removeFile" >删除文件</Button>
  • 2.data数据
    data() {
            return {
                file:null,
                limitNum:1,
                fileList:[],
            }
    }
  • 3.methods里面 uploadFile方法里面请注意 headers
  removeFile() {
                this.file=null;
            },
            exceedFile(file) {
                // this.$Message.warning(`只能选择 ${this.limitNum} 个文件,当前共选择了 ${files.length + fileList.length} 个`);
            },
            handleUpload (file) {
                this.file = file;
                return false;
            },
            uploadFile(file) {

                let formData = new FormData();
                formData.append('file', this.file);
                console.log(formData);
                this.axios({
                    method: 'post',
                    url: "/sip/uploadFile",
                    headers: {
                        'Content-type': 'multipart/form-data',
                    },
                    data: formData
                }).then(function (response) {
                    this.file = null;
                    console.log(response.data.code);
                    if (response.data.code === "200") {
                        this.$Message.info("上传成功");
                    } else {
                        this.$Message.warning("上传失败,请确认数据格式!!");
                    }
                  
                }.bind(this)).catch(function (error) {
                    alert(error);
                });
            },
  • 4.后台代码:
    @PostMapping("/sip/uploadFile")
    public String uploadFile(MultipartFile file){
        String res = sipService.uploadFile(file);
        return res;
    }

来吧,展示:

upload.png

Last modification:August 7th, 2020 at 04:09 pm
如果觉得我的文章对你有用,请随意赞赏