directly on the code
Vue code upload file component, using element-plus
<el-upload
ref="upload"
class="upload-files"
action=""
name="files"
multiple
:auto-upload="false"
:file-list="fileList"
:on-change="handleChange"
style="margin-top: 20px"
>
<el-button slot="trigger" type="primary">选取文件</el-button>
</el-upload>
<div slot="footer" class="dialog-footer">
<el-button type="primary" @click="submitUpload">保存</el-button>
</div>
Here, manual upload is used. After selecting the file, click Save to trigger the upload operation.
script code
// 上传文件数组
const fileList = ref([])
// 文件改变时回调钩子
const handleChange = (file, files) => {
// file是当前上传的文件,files是当前所有的文件,
// 不懂得话可以打印一下这两个数据 就能明白
fileList.value = files
}
// 测试多文件上传
const submitUpload = async () => {
let formData = new FormData()
formData.append('name', 'myk')
fileList.value.forEach(item => {
// 这里有个坑,在将文件append到formData的时候, item其实并不是真是数据 item.raw才是
formData.append('files', item.raw)
})
// 这里是发送请求,注意 headers: {'Content-Type': 'multipart/form-data'}
let result = await requestUtil.fileUpload('/testUpload', formData)
console.log(result)
}
If you don’t add .raw in this place, you can see that the files are [object Object] and it is passed to the background as a String type.
You use MultipartFile[] to receive this String type "[object Object]", which is definitely not possible.
It will give you an error Field error in object 'testUploadVo' on field 'files': rejected value [[object Object]]
Let's try adding .raw again. We can see that the files field is binary, and the request is sent successfully.
Take a look at background printing
The file can indeed be received, then try multiple files
Multiple files can also be received
Now let's look at the code behind
Create an entity class to receive parameters
package com.mayk.controller;
import lombok.Data;
import org.springframework.web.multipart.MultipartFile;
/**
* @author: mayk
* @date: 2023/4/13
*/
@Data
public class TestUploadVo {
private String name;
private MultipartFile[] files;
}
When creating a controller
package com.mayk.controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
/**
* @author: mayk
* @date: 2023/4/13
*/
@RestController
@CrossOrigin
public class TestUpload {
@PostMapping("/testUpload")
public String testUpload(TestUploadVo testUploadVo) {
for (MultipartFile file : testUploadVo.getFiles()) {
System.out.println(file.getOriginalFilename());
}
System.out.println(testUploadVo.getName());
return "ok";
}
}
No need to add @requestBody because this is submitted by the front end using FromData
Such a manual upload of multiple files is complete
Welcome to give advice