使用AJAX的文本内容和FileUpload [英] Text Content and FileUpload with AJAX
问题描述
我正在为我的公司编写一个客户端数据库系统。没有太多花哨的东西,但是它会做应有的事情。
现在所有基本的文本内容都已完成,我想在其中添加一些文件管理。
I am writting a client database system for my company. Not much fancy stuff, but it does what it should. Now that all the basic "text" stuff is done I want to add some filemanagement into it.
我有几种形式可以通过以下方式发送到后端
I have several forms which get send to the backend with ajax and then written into the db in the model.
其中某些表单计划上传文档文件。
Some of these forms are planned to have a document file upload.
是否可以使用AJAX处理正常值提交和文件提交?
Is there a way to handle normal value submits and a file submit with AJAX ?
让我给您一个FORM示例:
Let me give you a FORM example:
<form action="SOMEPATH/LOGIC_FILE.php" action="POST" enctype= multipart/form-data>
<label for="name">
<input type="text" id="name" name="name" />
</label>
<label for="somethingElse">
<input type="text" id="somethingElse" name="somethingElse" />
</label>
<label for="fileUpload">
<input type="file" />
</label>
</form>
AJAX示例:
var name = $('#name').val();
var somethingElse = $('#somethingElse').val();
var dataArr = { 'name':name, 'somethingElse':somethingElse};
MYELEMENT.click(function(e){
e.preventEventDefault();
$.ajax({
url: "PATH/logic/logic_update_client_allg.php",
type: "POST",
data: allgArray,
success: function(dataArr){
// works
},
error: function(){
// doesnt work
}
});
}
那就是我处理输入值的方式
Thats how I handle my INPUT VALUE submit
我如何继续以这种形式上传文件
How can I proceed to also upload a file with this form
谢谢
推荐答案
对于Ajax上传,您需要使用 xmlHttpRequest
在 jQuery.ajax()
方法中已经可用,但是使用了 FormData
。
For ajax uploads you need to use xmlHttpRequest
which is already available in the jQuery.ajax()
method, but with use of FormData
.
如果您不针对IE旧版本(例如7,8),则可以使用 FormData
。需要注意的一件事是,您必须设置 contentType,pr ocessData
到 false
。
If you are not targeting IE legacy versions, like 7,8 you can use FormData
. One thing to be noticed that you have to set contentType, processData
to false
.
请参见以下示例:
var name = $('#name').val();
var somethingElse = $('#somethingElse').val();
var fd = new FormData();
var dataArr = {
name: name,
somethingElse: somethingElse,
file : fd.append('file', $('#fileUpload').get(0).files[0]) // put the file here
};
MYELEMENT.click(function(e) {
e.preventDefault();
$.ajax({
url: "PATH/logic/logic_update_client_allg.php",
type: "POST",
data: dataArr, //<----post here the files and other values
processData: false, // tell jQuery not to process the data
contentType: false // tell jQuery not to set contentType
success: function(dataArr) {
// works
},
error: function() {
// doesnt work
}
});
});
这篇关于使用AJAX的文本内容和FileUpload的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!