前端js
let formData = new FormData($('#formId')[0]);
// https://developer.mozilla.org/zh-CN/docs/Web/API/FormData
// void append(DOMString name, Blob value, optional DOMString filename);
formData.append('files', file, file.name);
$.ajax({
cache: true,
type: "POST",
url: "/app/goods/save",
data: formData,//
async: false,
processData:false,
contentType: false,
error: function (request) {
parent.layer.alert("Connection error");
},
success: function (data) {
if (data.code == 0) {
parent.layer.msg("操作成功");
parent.reLoad();
var index = parent.layer.getFrameIndex(window.name); // 获取窗口索引
parent.layer.close(index);
} else {
parent.layer.alert(data.msg)
}
}
});
Ajax 使用 FormData做为data的参数时 出现Illegal invocation
processData用于对data参数进行序列化处理,默认值是true。默认情况下发送的数据将被转换为对象,如果不希望把File转换,需要设置为false
processData:false,
contentType: false
后台
private MultipartFile[] files;
MultipartFile[] files = goods.getFiles();
if (!ObjectUtils.isEmpty(files)) {
Arrays.asList(files).forEach(file -> {
UploadFileResponse fileResponse = fileStorageService.uploadFileResponse(file);
String filePath = fileResponse.getFilePath();
logger.debug("filePath: {}", filePath);
AppImage appImage = new AppImage();
appImage.setId(IDGenerate.id());
appImage.setPath(filePath);
appImage.setCreatedAt(new Date());
appImage.setFid(id);
imageService.save(appImage);
});
}
public UploadFileResponse uploadFileResponse(MultipartFile file) {
String contentType = file.getContentType();
String originalFilename = file.getOriginalFilename();
Map<String, String> data = new HashMap<String, String>();
String fileName = UUID.randomUUID().toString();
//originalFilename = originalFilename.substring(0, originalFilename.lastIndexOf("."));
String ext = originalFilename.substring(originalFilename.lastIndexOf("."), originalFilename.length());
fileName = fileName + ext;
String filePath = storeFile(file, fileName);
String fileDownloadUri = ServletUriComponentsBuilder.fromCurrentContextPath()
.path("system/file/download-file")
.path(filePath)
.toUriString();
UploadFileResponse fileResponse = UploadFileResponse.builder()
.originFileName(originalFilename)
.fileType(contentType)
.size(file.getSize())
.fileDownloadUri(fileDownloadUri)
.fileName(fileName)
.filePath(filePath)
.build();
return fileResponse;
}