前端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的參數(shù)時(shí) 出現(xiàn)Illegal invocation
processData用于對(duì)data參數(shù)進(jìn)行序列化處理,默認(rèn)值是true。默認(rèn)情況下發(fā)送的數(shù)據(jù)將被轉(zhuǎn)換為對(duì)象,如果不希望把File轉(zhuǎn)換,需要設(shè)置為false
processData:false,
contentType: false
后臺(tái)
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;
}