没有jquery或iframes的AJAX文件上传/表单提交? [英] AJAX file upload/form submit without jquery or iframes?
问题描述
是否可以在没有jQuery或IFrame的情况下提交AJAX表单(所以只是纯JavaScript)?我正在发送一个有效的struts fileUploadAction。动作的代码是否仍然适用于异步提交,或者是否需要添加异步表单提交?
Is it possible to do an AJAX form submit without jQuery or IFrames (so just pure JavaScript)? I'm currently sending to a struts fileUploadAction that works. Would the action's code still work with the asynchronous submit, or are there additions required to pick up the async form submit?
我正在使用struts 1.x和当前的表单是:
I am using struts 1.x and current my form is:
<html:form action="fileUploadAction" method="post" enctype="multipart/form-data">
...form elements...
<html:file property="theFile" />
...other elements...
</html:form>
是否可以提交此表格,从而使用AJAX上传文件?
Can this form be submitted, and thus the file uploaded with AJAX?
推荐答案
如果我理解你是对的,你可以使用以下代码上传文件异步。根据需要修改它
If I understood you correct, you can use the following code to upload the file async. Modify it as you like
var AjaxFileUploader = function () {
this._file = null;
var self = this;
this.uploadFile = function (uploadUrl, file) {
var xhr = new XMLHttpRequest();
xhr.onprogress = function (e) {
...
};
xhr.onload = function (e) {
...
};
xhr.onerror = function (e) {
...
};
xhr.open("post", uploadUrl, true);
xhr.setRequestHeader("Content-Type", "multipart/form-data");
xhr.setRequestHeader("X-File-Name", file.name);
xhr.setRequestHeader("X-File-Size", file.size);
xhr.setRequestHeader("X-File-Type", file.type);
xhr.send(file);
};
};
AjaxFileUploader.IsAsyncFileUploadSupported = function () {
return typeof (new XMLHttpRequest().upload) !== 'undefined';
}
if (AjaxFileUploader.IsAsyncFileUploadSupported) {
ajaxFileUploader = new AjaxFileUploader();
$("form").submit(function () {
var uploader = $("#fileUploader")[0];
if (uploader.files.length == 0) {
return;
} else {
ajaxFileUploader.uploadFile(
"/YourUploadUrl",
uploader.files[0]);
}
return false;
});
}
要上传表单,请使用FormData类,使用表单值填充并发布它与XHR。
To upload the form use the FormData class, populate it with form values and post it with XHR.
更新:
对于HTML4,请尝试以下
Update: For HTML4 try the following
- http://www.albanx.com/?pid=5&subid=21
- Asynchronous file upload (AJAX file upload) using jsp and javascript
这篇关于没有jquery或iframes的AJAX文件上传/表单提交?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!