我在尝试将多个文件上传到我的ajax请求时遇到以下错误。以下是日志和我的脚本中的错误。看起来它在ajax请求上失败了,因为console.logs按预期打印出来。我不知道这意味着什么?
<h1>HTTP Status 400 - Required MultipartFile[] parameter 'files' is not present</h1>
AJAX请求:
function makeProgress(number){
var url = getRelativeURL("web/fileUpload");
var formData = new FormData();
formData.append('number', number);
fls = document.getElementById("attachmentFileUploadInput").files; //length of files...
console.log(fls);
for(j=0;j<fls.length;j++){
formData.append('files[]', fls[j]); //note files[] not files
}
//formData.append('file', $('input[type=file]')[0].files[0]);
console.log("form data " + formData);
$.ajax({
url : url,
data : formData[j],
processData : false,
contentType : false,
type : 'POST',
success : function(data) {
FileUploadVisible(true);
$('#attachmentModal').modal('hide')
$(':input','#attachmentModal').val("");
$("#pbarmain").hide();
$("#pbar").hide();
$("#actionPlanDiv").hide();
setObjectEnabled('#Upload',false);
},
error : function(err) {
FileUploadErrorVisible(true);
}
});
}
服务器端:
private static String UPLOADED_FOLDER = "C://temp//";
@RequestMapping(value = { "/fileUpload" }, method = RequestMethod.POST)
@ResponseBody
public String uploadFile( @RequestParam("number") String number, @RequestParam("files") MultipartFile[] files, MultipartHttpServletRequest req, HttpServletResponse res)
{
for (MultipartFile file : files) {
try {
File directory = new File(UPLOADED_FOLDER + number);
if (! directory.exists()){
directory.mkdir();
}
byte[] bytes = file.getBytes();
Path path = Paths.get(UPLOADED_FOLDER + number + "//" + file.getOriginalFilename());
Files.write(path, bytes);
logger.info("You have successfully uploaded '" + file.getOriginalFilename() + "'");
return("File Uploaded");
} catch (Exception e) {
res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
logger.error("Failed to upload file '" + file.getOriginalFilename() + "'", e);
return("File Not Uploaded");
}
}
return "redirect:/fileUpload";
}
}
配置
@Bean(name = "multipartResolver")
public CommonsMultipartResolver commonsMultipartResolver(){
CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver();
commonsMultipartResolver.setDefaultEncoding("utf-8");
commonsMultipartResolver.setMaxUploadSize(5000000); // 5000000 -> 5MB
return commonsMultipartResolver;
} }