我的Ajax发布存在问题。 阿贾克斯:
var formData = new FormData();
formData.append('file', files);
formData.append("url", url);
$.ajax({
url : "/servisDetail/uploadSoubor",
type : 'GET',
processData: false,
contentType: false,
data : formData,
success : function(response) {
console.log(response);
//vypisPrilohy(response);
},
error: function (xhr) { }
});
和Java:
@RequestMapping(value = "/servisDetail/uploadSoubor", method= RequestMethod.GET)
public @ResponseBody
ModelMap servisDetailUploadFile(@RequestParam(value = "file",required = false) MultipartFile soubor,
@RequestParam(value = "url",required = false) String odkaz,
Locale locale){
ModelAndView model = new ModelAndView();
System.err.println("File: " + soubor + " and " + odkaz);
return model.getModelMap();
}
但是打印到控制台的是:File:null和null。
没有processData:false我有一个ajax错误:非法调用 并输入get或post仍然相同
有人知道如何解决吗?
答案 0 :(得分:0)
这是因为您没有将正确的文件附加到formData。请参阅How to use FormData for ajax file upload。我尝试了下面的代码,它顺利通过了测试。
<html>
<head>
<title>Test</title>
</head>
<body>
<input type="file" name="file">
<script src="jquery-3.3.1.min.js"></script>
<script type="text/javascript">
$(function(){
$('[name=file]').on('change', function(){
var formData = new FormData();
formData.append('file', $(this)[0].files[0]);
formData.append("url", 'https://stackoverflow.com/questions/51235726/spring-ajax-send-value-but-null');
$.ajax({
url : "/servisDetail/uploadSoubor",
type : 'POST',
processData: false,
contentType: false,
data : formData,
success : function(response) {
console.log(response);
//vypisPrilohy(response);
},
error: function (xhr) { }
});
})
});
</script>
</body>
</html>
我在控制台中得到了类似File: org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile@4b5db24c and https://stackoverflow.com/questions/51235726/spring-ajax-send-value-but-null
的输出
答案 1 :(得分:0)
最后,我做了不同的事情。谢谢。
$.ajax({
url : "/servisDetail/uploadSoubor",
type : 'GET',
dataType: 'json',
contentType: 'application/json',
data : {
fileSize: files.size,
fileName: files.name,
url: url
},
success : function(response) {
console.log(response);
vypisPrilohy(response);
},
error: function (xhr) { }
});
并使用ByteArrayInputStream byteArray = new ByteArrayInputStream(new byte[fileSize]);