vue3+elementplus+el-upload,文件上传,带参数传递到后台,亲测有用

网上查阅了很多资料,结果都不尽人意,废话不多说,直接上代码。

前端代码:

<el-upload
 :on-preview="previewFile"
  limit="1"
  :on-change="changeFile"
  :auto-upload="false" 
  :data="uploadForm.data">
   <template #trigger>
      <el-button size="small" type="primary">选取附件</el-button>
   </template>
   <el-button style="margin-left: 10px;" size="small" type="success" 
    @click="submitUpload">上传到服务器</el-button>
</el-upload>

其中:

1.on-preview: 点击文件列表中已上传的文件时的钩子(一般用作文件预览,在这里不重要)

2.on-change: 文件状态改变时的回调函数,可以用来给file赋值

const file = ref()

const changeFile = (uploadFile: UploadFile) => {
    file.value = uploadFile;
}

3. :auto-upload="false" 这一步比较重要,必须要把自动上传关闭,因为我们会自己写方法上传。

4. :data="uploadForm.data" 需要携带的参数

const uploadForm = reactive({
    data: {
        fileId: '',
        name: '',
        type: ''
    }
})

5. 重要的 submitLicenseUpload 方法来了:

const submitUpload = () => {
    const jsonStr = JSON.stringify(uploadForm.data);
    const blob = new Blob([jsonStr], {
        type: 'application/json'
    });
    let formData = new FormData();
    formData.append("obj", blob);
    // 这里很重要 file.value.raw才是真实的file文件,file.value只是一个Proxy代理对象
    formData.append("file", file.value.raw);
    let url = '你的后端url'
    let method = 'post'
    let headers =
    {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    };
    axios({
        method,
        url,
        data: formData,
        headers
    }).then(res => {
        console.log(res);
        console.log(res.data);
    });
}

后端代码(springboot controller):

    @PostMapping("upload")
    @Operation(summary = "上传")
    @ResponseBody
    //注意  带参数的话,这里需要用RequestPart,RequestParam进不来
    public Result<YourClass> upload(@RequestPart("file") MultipartFile file, @RequestPart("obj") AttachmentVO vo) throws Exception {

        
        return null;
}

至此,结束!

  • 13
    点赞
  • 50
    收藏
    觉得还不错? 一键收藏
  • 9
    评论
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值