如何使用angular发送多个文件。
一个文件可以正常工作,没有任何问题。已使用的multipart
文件。
let formdata = new FormData();
formdata.append("file", file);
formdata.append("param", obj);
这将以二进制形式出现在请求中。
如何一起发送多个文件?如果我使用的列表会像这样-[object File][object File]
后端无法解析
后端服务器。
@RequestParam(name = "param", required = true) String param,
@RequestParam(name = "file", required = false) MultipartFile[] file
答案 0 :(得分:1)
您可以创建一个通用功能,该功能可用于单张和多张图片上传,也可以在多个模块中使用它
如下所示
第1步:按以下步骤在共享服务中创建常用功能
/**
* @description: this function will set the image in form data in returns it in the response
* @param e : file object
* @param extention : allowed extentions which allow to upload
* @param multiple : single or multiple
*/
uploadImage(e, extention = ['png', 'jpeg', 'jpg'], multiple = "") {
let fileLength = e.target.files.length;
let response: any = {};
response.images = [];
let uploadFile: any;
if (fileLength > 1 || multiple != "") {
for (let eachFile of e.target.files) {
let returnImage = this.setImageInResponse(eachFile, extention);
if (!returnImage.ImageError) {
response.images.push(returnImage);
} else {
response.ImageError = returnImage.ImageError;
}
}
} else {
uploadFile = e.target ? e.target.files[0] : null;
if (uploadFile) {
response = this.setImageInResponse(uploadFile, extention);
}
}
return response;
}
/**
* @desc: this function will set individual file object in from data
* @param uploadFile : object of single file
* @param extention : allowed extentsions
*/
setImageInResponse(uploadFile, extention) {
let response: any = {};
let tmpExtension = extention;
let tmpFileExtension = uploadFile.name.split('.').pop().toLowerCase();
if (tmpExtension.indexOf(tmpFileExtension) > -1) {
response.uploadFile = uploadFile;
var reader = new FileReader();
reader.onload = (event: ProgressEvent) => {
response.uploadImgUrl = reader.result;
}
reader.readAsDataURL(uploadFile);
}
else {
let errorString = tmpExtension.toString();
response.ImageError = "You can upload only " + errorString;
}
return response;
}
第2步:使用所需参数调用上传图片功能
因此您将收到要在模块中获取的单个或多个完整的表单数据
然后执行下一步