关于上传多个图片带其他参数调用上传接口报错:"Current request is not a multipart request"

3,770 阅读1分钟

记录自己的踩坑:上传多个图片带其他参数调用上传接口报错:"Current request is not a multipart request",上网查了下这个问题。

看到了几个解决办法: 第一种方法:就是将header里面的Content-Type:改为“multipart/form-data”,但是改了之后接口报下面的错误: Could not parse multipart servlet request; nested exception is java.io.IOException: org.apache.tomcat.util.http.fileupload.FileUploadException: the request was rejected because no multipart boundary was found",对于我来说此方法并没有解决我的问题

第二种方法: 有人说正确的做法是删除Content-Type就行了,但是我将Content-Type设置为false,设置为"",设置为null,都没有解决我的问题。还有人说这个Content-Type不用设置,会自己识别多文件上传类型,也就是下面这样

微信截图_20230223152605.png

最后我问了大佬,大佬说要把其他参数一起放formData里面

//上传图片的数组
const imgArr=ref<string[]>([])
// 上传图片
let formData = new FormData()
const updateImg = (files: { length: number; forEach: (arg0: (element: any) => void) => void; content: any; file: string | Blob | File; })=>{
    
    if(files.length>1){
        files.forEach((element) => {
            imgArr.value.push(element.content)
            formData.append("files",element.file)
        });
    }else{
        imgArr.value.push(files.content)
        formData.append("files",files.file)
    }
}

然后上传的时候将这些参数(dayId,branchId等)一起放进去就好了,还真是不用设置header里面的Content-Type

//发送
const send = ()=>{
    // formData.append("dayId","20230217")
    formData.append("dayId",date as string)
    formData.append("branchId",branchId as string)
    formData.append("content",message.value)
    console.log(formData);
    
    Api.sendRBack(formData).then((res)=>{
        getRDetail()
        sendSuccss()
    })
    
}

这样写之后就直接发送成功了,后台也能直接解析出参数和图片存入数据库了,展示一下效果

485a21cdcdb44cf935dda4657363eb2.jpg