以下是我的代码: jsp代码
<form:form name="uploadForm" id="fileUploadForm" method="POST" enctype="multipart/form-data">
<input type="file" id="file" name="file" value="Import" ">
<input type = "hidden" name="strategy" />
<input type="button" value="Import" id="Import" />
</form:form>
jquery片段下面绑定了导入按钮的点击功能
$("#Import").click(function(){
filePath = document.getElementById("file").value;
}
在上面的变量filePath中分配了filePath值 下面的代码片段对控制器进行Ajax调用
var formData = new FormData($('#fileUploadForm')[0]);
formData.append('tax_file', $('input[type=file]')[0].files[0]);
$.ajax({
url: 'ajax/getuploadFile.html',
data: {
formData:formData, strategy:strategy,
},
type: "POST",
contentType: false,
processData: false,
success : function(response){
alert(response);
},
error: function() {
alert("Inside");
}
});
java控制器类
@RequestMapping(value = "ajax/getuploadFile.html", method = RequestMethod.POST)
public @ResponseBody String getuploadFile(HttpServletRequest request,
@RequestParam("formData") MultipartFile attachment,
@RequestParam("strategy") String strategy,
) throws Exception {
任何人都可以帮助我..我面临的例外是当前请求不是多部分请求。我们试图通过jsp代码中提到的导入功能导入.csv文件。
答案 0 :(得分:0)
“formData”已包含“文件”和“策略”,因此您只需:data: formData
var formData = new FormData($('#fileUploadForm')[0]);
formData.append('tax_file', $('input[type=file]')[0].files[0]);
$.ajax({
url: 'ajax/getuploadFile.html',
data: formData,
type: "POST",
contentType: false,
processData: false,
success : function(response){
alert(response);
},
error: function() {
alert("Inside");
}
答案 1 :(得分:0)
请尝试这种方式:
Java控制器
@Controller
public class TestController {
@RequestMapping("/test")
@ResponseBody
public String upload(
@RequestPart("file") MultipartFile multipartFile,
@RequestParam("strategy") String strategy) {
return "ok";
}
@RequestMapping
public ModelAndView index() {
return new ModelAndView("/WEB-INF/jsp/upload.jsp");
}
}
JSP文件
<html>
<body>
<form name="uploadForm" id="fileUploadForm" method="POST"enctype="multipart/form-data">
<input type="file" id="file" name="file" value="Import"">
<input type="hidden" name="strategy" />
<input type="submit" value="Import" id="Import" />
</form>
<script type="text/javascript"
src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
$('form[name="uploadForm"]').submit(function(event){
event.preventDefault();
var formData = new FormData($('#fileUploadForm')[0]);
formData.append('file', $('input[type=file]')[0].files[0]);
$.ajax({
url: '/test',
data: formData,
type: "POST",
contentType: false,
processData: false,
success : function(response){
alert(response);
},
error: function() {
alert("Inside");
}
});
return false;
});
</script>
</body>
</html>
我已经尝试过测试了。它工作正常。