php 如何使用jquery序列化进行文件上传
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4545081/
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
how to do file upload using jquery serialization
提问by kamikaze_pilot
So I have a form and I'm submitting the form through ajax using jquery serialization function
所以我有一个表单,我正在使用 jquery 序列化功能通过 ajax 提交表单
serialized = $(Forms).serialize();
$.ajax({
type : "POST",
cache : false,
url : "blah",
data : serialized,
success: function(data) {
}
but then what if the form has an <input type="file">
field....how do I pass the file into the form using this ajax serialization method...printing $_FILES doesn't output anything
但是如果表单有一个<input type="file">
字段怎么办....我如何使用这个 ajax 序列化方法将文件传递到表单中...打印 $_FILES 不输出任何内容
采纳答案by Darin Dimitrov
A file cannot be uploaded using AJAX because you cannot access the contents of a file stored on the client computer and send it in the request using javascript. One of the techniques to achieve this is to use hidden iframes. There's a nice jquery form pluginwhich allows you to AJAXify your forms and it supports file uploadsas well. So using this plugin your code will simply look like this:
无法使用 AJAX 上传文件,因为您无法访问存储在客户端计算机上的文件内容并使用 javascript 在请求中发送它。实现此目的的技术之一是使用隐藏的 iframe。有一个很好的jquery 表单插件,它允许您对表单进行 AJAX 化,它也支持文件上传。因此,使用此插件,您的代码将如下所示:
$(function() {
$('#ifoftheform').ajaxForm(function(result) {
alert('the form was successfully processed');
});
});
The plugin automatically takes care of subscribing to the submit
event of the form, canceling the default submission, serializing the values, using the proper method and handle file upload fields, ...
该插件会自动处理订阅submit
表单事件、取消默认提交、序列化值、使用正确的方法并处理文件上传字段,...
回答by Shaiful Islam
You can replace the return from serialize()
with a FormData
object instead. It works for any type of form
您可以serialize()
用一个FormData
对象替换 return from 。它适用于任何类型的表格
$(document).on("submit", "form", function(event)
{
event.preventDefault();
var url=$(this).attr("action");
$.ajax({
url: url,
type: $(this).attr("method"),
dataType: "JSON",
data: new FormData(this),
processData: false,
contentType: false,
success: function (data, status)
{
},
error: function (xhr, desc, err)
{
}
});
});
回答by Maryam Zakani
var form = $('#job-request-form')[0];
var formData = new FormData(form);
event.preventDefault();
$.ajax({
url: "/send_resume/", // the endpoint
type: "POST", // http method
processData: false,
contentType: false,
data: formData,
It worked for me! just set processData and contentType False.
它对我有用!只需将 processData 和 contentType 设置为 False。
回答by Renish Patel
HTML
HTML
<form name="my_form" id="my_form" accept-charset="multipart/form-data" onsubmit="return false">
<input id="name" name="name" placeholder="Enter Name" type="text" value="">
<textarea id="detail" name="detail" placeholder="Enter Detail"></textarea>
<select name="gender" id="gender">
<option value="male" selected="selected">Male</option>
<option value="female">Female</option>
</select>
<input type="file" id="my_images" name="my_images" multiple="" accept="image/x-png,image/gif,image/jpeg"/>
</form>
JavaScript
JavaScript
var data = new FormData();
//Form data
var form_data = $('#my_form').serializeArray();
$.each(form_data, function (key, input) {
data.append(input.name, input.value);
});
//File data
var file_data = $('input[name="my_images"]')[0].files;
for (var i = 0; i < file_data.length; i++) {
data.append("my_images[]", file_data[i]);
}
//Custom data
data.append('key', 'value');
$.ajax({
url: "URL",
method: "post",
processData: false,
contentType: false,
data: data,
success: function (data) {
//success
},
error: function (e) {
//error
}
});
PHP
PHP
<?php
echo '<pre>';
print_r($_POST);
print_r($_FILES);
echo '</pre>';
die();
?>
回答by Rossco
You can upload files via AJAX by using the FormData method. Although IE7,8 and 9 do not support FormData functionality.
您可以使用 FormData 方法通过 AJAX 上传文件。尽管 IE7、8 和 9 不支持 FormData 功能。
$.ajax({
url: "ajax.php",
type: "POST",
data: new FormData('form'),
contentType: false,
cache: false,
processData:false,
success: function(data) {
$("#response").html(data);
}
});
回答by RameshN
$(document).on('click', '#submitBtn', function(e){
e.preventDefault();
e.stopImmediatePropagation();
var form = $("#myForm").closest("form");
var formData = new FormData(form[0]);
$.ajax({
type: "POST",
data: formData,
dataType: "json",
url: form.attr('action'),
processData: false,
contentType: false,
success: function(data) {
alert('Sucess! Form data posted with file type of input also!');
}
)};});
By making use of new FormData()
and setting processData: false, contentType:false
in ajax call submission of form with file input worked for me
通过在 ajax 调用中使用new FormData()
和设置processData: false, contentType:false
带有文件输入的表单提交对我有用
Using above code I am able to submit form data with file field also through Ajax
使用上面的代码,我也可以通过 Ajax 提交带有文件字段的表单数据
回答by Jehad Ahmad Jaghoub
hmmmm i think there is much efficient way to make it specially for people want to target all browser and not only FormDatasupported browser
嗯,我认为有很多有效的方法可以专门针对想要针对所有浏览器而不仅仅是 FormData支持的浏览器的人
the idea to have hidden IFRAMEon page and making normal submit for the From inside IFrame example
在页面上隐藏IFRAME并为 From inside IFrame 示例正常提交的想法
<FORM action='save_upload.php' method=post
enctype='multipart/form-data' target=hidden_upload>
<DIV><input
type=file name='upload_scn' class=file_upload></DIV>
<INPUT
type=submit name=submit value=Upload /> <IFRAME id=hidden_upload
name=hidden_upload src='' onLoad='uploadDone("hidden_upload")'
style='width:0;height:0;border:0px solid #fff'></IFRAME>
</FORM>
most important to make a target of form the hidden iframe IDor nameand enctype multipart/form-datato allow accepting photos
最重要的是将表单的目标设置为隐藏的 iframe ID或名称并输入multipart/form-data以允许接受照片
javascript side
javascript端
function getFrameByName(name) {
for (var i = 0; i < frames.length; i++)
if (frames[i].name == name)
return frames[i];
return null;
}
function uploadDone(name) {
var frame = getFrameByName(name);
if (frame) {
ret = frame.document.getElementsByTagName("body")[0].innerHTML;
if (ret.length) {
var json = JSON.parse(ret);
// do what ever you want
}
}
}
server Side Example PHP
服务器端示例 PHP
<?php
$target_filepath = "/tmp/" . basename($_FILES['upload_scn']['name']);
if (move_uploaded_file($_FILES['upload_scn']['tmp_name'], $target_filepath)) {
$result = ....
}
echo json_encode($result);
?>
回答by Rahul Patel
HTML5 introduces FormData
class that can be used to file upload with ajax.
HTML5 引入FormData
了可用于使用 ajax 上传文件的类。
FormData support starts from following desktop browsers versions. IE 10+, Firefox 4.0+, Chrome 7+, Safari 5+, Opera 12+
FormData 支持从以下桌面浏览器版本开始。IE 10+、Firefox 4.0+、Chrome 7+、Safari 5+、Opera 12+