上传文件 + 表单数据 + Spring MVC + JQuery
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17498426/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Upload file + Form Data + Spring MVC + JQuery
提问by Rocco Saya
I'll try to make this question as simple as I can. I want to upload a file withadditional form data via an AJAX submission using JQuery (but also for it to be compatible with ie 7 or ie 8, and asynchronous too)
我会尽量让这个问题简单化。我想通过使用 JQuery 的 AJAX 提交上传一个带有附加表单数据的文件(但也为了它与 ie 7 或 ie 8 兼容,并且也是异步的)
Without the submit being an AJAX submission via JQuery, the process works fine. Namely I did the following:
如果提交不是通过 JQuery 的 AJAX 提交,则该过程工作正常。即我做了以下事情:
- declared CommonsMultipartResolver
- In controller wrote this handler method
- 声明的 CommonsMultipartResolver
- 在控制器中编写了这个处理程序方法
@RequestMapping(value="/processfileupload", method = RequestMethod.POST) public @ResponseBody String handleFileUpload(UploadForm data, BindingResult result) throws Exception {
@RequestMapping(value="/processfileupload", method = RequestMethod.POST) public @ResponseBody String handleFileUpload(UploadForm data, BindingResult result) 抛出异常 {
....
}
}
Where UploadForm is a Spring MVC form object which I bound to the form. Also, I bound the formObject in Spring's form tag like so: enctype="multipart/form-data" .. etc..
其中 UploadForm 是我绑定到表单的 Spring MVC 表单对象。另外,我在 Spring 的表单标签中绑定了 formObject,如下所示: enctype="multipart/form-data" .. 等等。
Like I said, works perfectly if it is NOT done via an Ajax call via JQuery. Once I tried to make it an Ajax call, the file is always null.
就像我说的,如果不是通过 JQuery 的 Ajax 调用来完成的话,它可以完美地工作。一旦我尝试使其成为 Ajax 调用,该文件始终为空。
Here is the Ajax call via JQuery
这是通过 JQuery 的 Ajax 调用
function submitFileUploadViaAjax() {
函数 submitFileUploadViaAjax() {
$.ajax({
url: "processfileupload",
data: $("#file_upload_form").serialize(),
type: "POST",
processData: false,
contentType: false,
success: function(data) {
$(response).html(data);
},
error: function (xhr, ajaxOptions, thrownError) {
if (xhr.readyState == 0 || xhr.status == 0) {
// not really an error
return;
} else {
alert("XHR Status = "+xhr.status);
alert("Thrown Error = "+thrownError);
alert("AjaxOptions = "+ajaxOptions)
}
}
});
}
}
I suspect the problem may be: data: $("#file_upload_form").serialize(),
我怀疑问题可能是:数据:$("#file_upload_form").serialize(),
I have read some suggested solutions for those with similar problems to use a formData object but have read that this won't be compatible with IE 7 or IE 8, is this true?
我已经为那些有类似问题的人阅读了一些建议的解决方案来使用 formData 对象,但读到这将与 IE 7 或 IE 8 不兼容,这是真的吗?
I head also read the JQuery file upload plug-in would work ( https://github.com/blueimp/jQuery-File-Upload/wiki/How-to-submit-additional-form-data) but I'm not sure if I'd be able to wire this into spring with spring's great way of binding form data to a form object and then just injecting it into a controller.
我还读了 JQuery 文件上传插件可以工作(https://github.com/blueimp/jQuery-File-Upload/wiki/How-to-submit-additional-form-data)但我不确定如果我能够使用 spring 将表单数据绑定到表单对象的好方法将其连接到 spring,然后只需将其注入控制器。
Does anyone have their thoughts on the best way to upload a file (relatively small) + have some form data, and be able to process this with a single endpoint in a spring mvc controller? And the solution so that it is compatible with most browsers, but especially will work with ie 7 or ie 8 (it's a requirement it work in those browsers.)
有没有人对上传文件(相对较小)+有一些表单数据的最佳方式有自己的想法,并且能够在 spring mvc 控制器中使用单个端点处理它?并且解决方案使其与大多数浏览器兼容,但尤其适用于 ie 7 或 ie 8(这是在这些浏览器中工作的要求。)
Thanks a bunch!
谢谢一堆!
- Rocco
- 罗科
回答by Habib Ksentini
File uploading using AJAX is possible: try this
可以使用 AJAX 上传文件:试试这个
Client Side : HTML
客户端:HTML
<input type="file" name="file" id="fileLoader" />
<input type="button" id="fileSubmit" value="Upload"/>
Client Side : JS
客户端:JS
var files = [];
$(document)
.on(
"change",
"#fileLoader",
function(event) {
files=event.target.files;
})
$(document)
.on(
"click",
"#fileSubmit",
function() {
processUpload();
})
function processUpload()
{
var oMyForm = new FormData();
oMyForm.append("file", files[0]);
$
.ajax({dataType : 'json',
url : "the url",
data : oMyForm,
type : "POST",
enctype: 'multipart/form-data',
processData: false,
contentType:false,
success : function(result) {
//...;
},
error : function(result){
//...;
}
});
}
Server Side : JAVA
服务器端:JAVA
@RequestMapping(method = RequestMethod.POST, value = "the url")
@ResponseBody
public void uploadFile(@RequestParam("file") MultipartFile multipartFile) {
//...
}
回答by arn-arn
this worked like a charm for me:
这对我来说就像一个魅力:
$('#formId').submit(function(evt) {
evt.preventDefault();
var formData = new FormData(this);
$.ajax({
type: 'POST',
url: "/url",
data:formData,
cache:false,
contentType: false,
processData: false,
success: function(data) {
alert('success');
},
error: function(data) {
alert('failed');
}
});
});
回答by Sheldon Menezes Chaves
To upload file, use formdata:
要上传文件,请使用 formdata:
function collectFormData(fields) {
var formData = new FormData();
for (var i = 0; i < fields.length; i++) {
var $item = $(fields[i]);
if ($item.attr('type') =="file"){
var file = $('input[type=file]')[0].files[0];
formData.append( $item.attr('name') , file);
} else {
formData.append( $item.attr('name') , $item.val());
}
}
return formData;
}
and send:
并且寄出:
var fields = form.find('input, textarea, select');
var formData = collectFormData(fields);
$.ajax({
url: form.attr('action'),
type: 'POST',
scriptCharset: "utf-8",
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
timeout: 600000,
success: function (response) {
if (response.status == "SUCCESS"){
console.log("SUCCESS...");
$( document ).trigger( "SUCCESS", [ response ] );
} else if (response.status == "FAIL"){
console.log("FAIL...");
clearErrors(form);
...
}
}
})
回答by user2627846
File uploading using AJAX is not possible. AJAX doesn't actually post forms to the server, it sends selected data to the server in the form of a POST or GET request. As javascript is not capable of grabbing the file from the users machine and sending it to the server, it's just not possible with AJAX. You have to resort to regular old form submit.
无法使用 AJAX 上传文件。AJAX 实际上并不向服务器发送表单,它以 POST 或 GET 请求的形式将选定的数据发送到服务器。由于 javascript 无法从用户机器获取文件并将其发送到服务器,因此 AJAX 无法实现。您必须求助于常规的旧表单提交。
Follow this link: http://viralpatel.net/blogs/ajax-style-file-uploading-using-hidden-iframe/for an example
按照此链接:http: //viralpatel.net/blogs/ajax-style-file-uploading-using-hidden-iframe/示例