Jquery ajax单文件上传

我知道这个问题已经被问了很多,我尝试了至少10个不同的代码来运行它没有成功。 我正在尝试使用jquery.ajax上传单个文件,但它不起作用。 下面的代码总是输出:’请选择一个文件’,因为文件的名称没有设置或其他东西

HTML:

jQuery的:

  $(function() $(document).ready(function(){ var files; $('input[type=file]').on('change', prepareUpload); function prepareUpload(event){ files = event.target.files; }; $(':button').click(function(){ var formData = new FormData(); $.each(files, function(key, value){ formData.append(key, value); }); alert(formData); $.ajax({ url: 'check.php', type: 'GET', data: formData, success:function(data){ $('#result').html(data); }, cache: false, contentType: false, processData: false }); }); }); 

});

PHP:

  if(isset($_GET['file'])){ $filename = $_FILES['file']['name']; if(isset($filename) && !empty($filename)){ echo 'sup my man?!'; }else{ echo 'please choose a file'; } }else{ echo 'not set'; } 

我不知道问题是什么,我知道它在FormData对象创建中,因为警报 – 好去,不起作用。

在此先感谢您的帮助。 BTW对我来说非常重要,它将用jquery编写。

经过几个小时的搜索和寻找答案,我终于成功了!!!!! 代码如下:))))

HTML:

      

jQuery的:

 $(function(){ $('#uploadBTN').on('click', function(){ var fd = new FormData($("#fileinfo")); //fd.append("CustomField", "This is some extra data"); $.ajax({ url: 'upload.php', type: 'POST', data: fd, success:function(data){ $('#output').html(data); }, cache: false, contentType: false, processData: false }); }); }); 

upload.php文件中,您可以访问使用$_FILES['file']传递的数据。

谢谢大家试图帮助:)

我从这里(带有一些变化) MDN获得了答案

A.从文件字段中抓取文件数据

首先要做的是将函数绑定到文件字段上的change事件和用于获取文件数据的函数:

 // Variable to store your files var files; // Add events $('input[type=file]').on('change', prepareUpload); // Grab the files and set them to our variable function prepareUpload(event) { files = event.target.files; } 

这会将文件数据保存到文件变量中供以后使用。

B.在提交时处理文件上传

提交表单时,您需要在自己的AJAX请求中处理文件上载。 添加以下绑定和function:

 $('form').on('submit', uploadFiles); // Catch the form submit and upload the files function uploadFiles(event) { event.stopPropagation(); // Stop stuff happening event.preventDefault(); // Totally stop stuff happening // START A LOADING SPINNER HERE // Create a formdata object and add the files var data = new FormData(); $.each(files, function(key, value) { data.append(key, value); }); $.ajax({ url: 'submit.php?files', type: 'POST', data: data, cache: false, dataType: 'json', processData: false, // Don't process the files contentType: false, // Set content type to false as jQuery will tell the server its a query string request success: function(data, textStatus, jqXHR) { if(typeof data.error === 'undefined') { // Success so call function to process the form submitForm(event, data); } else { // Handle errors here console.log('ERRORS: ' + data.error); } }, error: function(jqXHR, textStatus, errorThrown) { // Handle errors here console.log('ERRORS: ' + textStatus); // STOP LOADING SPINNER } }); } 

这个函数的作用是创建一个新的formData对象并将每个文件附加到它。 然后它将该数据作为请求传递给服务器。 需要将2个属性设置为false:

  • processData – 因为jQuery会将文件数组转换为字符串,而服务器无法将其拾取。
  • contentType – 将此设置为false,因为jQuery默认为application / x-www-form-urlencoded并且不发送文件。 将其设置为multipart / form-data也似乎不起作用。

C.上传文件

快速和脏的PHP脚本上传文件并传回一些信息:

  'There was an error uploading your files') : array('files' => $files); } else { $data = array('success' => 'Form was submitted', 'formData' => $_POST); } echo json_encode($data); ?> 

IMP:不要使用它,写自己的。

D.处理表单提交

上传function的成功方法将从服务器发回的数据传递给提交function。 然后,您可以将其作为post的一部分传递给服务器:

 function submitForm(event, data) { // Create a jQuery object from the form $form = $(event.target); // Serialize the form data var formData = $form.serialize(); // You should sterilise the file names $.each(data.files, function(key, value) { formData = formData + '&filenames[]=' + value; }); $.ajax({ url: 'submit.php', type: 'POST', data: formData, cache: false, dataType: 'json', success: function(data, textStatus, jqXHR) { if(typeof data.error === 'undefined') { // Success so call function to process the form console.log('SUCCESS: ' + data.success); } else { // Handle errors here console.log('ERRORS: ' + data.error); } }, error: function(jqXHR, textStatus, errorThrown) { // Handle errors here console.log('ERRORS: ' + textStatus); }, complete: function() { // STOP LOADING SPINNER } }); } 

最后的说明

此脚本仅为示例,您需要同时处理服务器和客户端validation以及通知用户文件上载发生的某种方式。 如果你想看到它工作,我在Github上为它做了一个项目。

引自