Upload files with Ajax and Jquery

无人久伴 提交于 2020-01-04 15:16:05

问题


I've been trying to figure out how to upload a file through ajax for the past several hours and nothing.

Here's the code: HTML:

<form action="" method="post" id="uploadForm" enctype="multipart/form-data">

  <input type="file" name="image" id="image">
  <input type="submit">

</form>

JS:

<script>

jQuery(document).ready(function(){  
  jQuery('form#uploadForm').on('submit', function(e){
    e.preventDefault();

    var file = jQuery('#image')[0].files[0];
    var form_data = new FormData( jQuery("form#uploadForm")[0] );
    form_data.append( 'image', file );

    jQuery.ajax({
      url: 'index.php?a=do',
      type: 'POST',
      processData: false,
      contentType: false,
      cache: false,
      data: form_data,
      success: function(response) {
        console.log(response);
      },
    });

    return false;

  });
});

</script>

PHP:

<?php 
$a = isset($_GET['a']) ? $_GET['a'] : '';
if($a <> '') {
  echo "result - ";
  var_dump($_POST);
  die();
}
?>

As a result I get an empty array, however if I leave the file field empty, then I get:

result - array(1) {
  ["image"]=>
  string(9) "undefined"
}

I've tried serialize(), serializeObject(), serializeArray(), $.param and every damn time I get "undefined function" error in console.

I went through dozens of similar questions on stackoverflow and nothing helped. I tried doing $.post instead of $.ajax and the "data" field which contains form_data is empty.

I need this for a Wordpress plugin and I'm trying to avoid using 3rd party JS plugins for the upload part.


回答1:


$_FILES is where you check for uploaded files not $_POST.
Also in your code you actually upload the file twice as it is in the form you instantiated the form data object with then you add it again with append. Do either

var form_data = new FormData( jQuery("form#uploadForm")[0] );

or

var form_data = new FormData();
form_data.append( 'image', file );



回答2:


<html>
<head>
<title>Ajax file upload</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function (e) {
$("#uploadimage").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "ajax_php_file.php", // Url to which the request is send
type: "POST",             // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false,       // The content type used when sending data to the server.
cache: false,             // To unable request pages to be cached
processData:false,        // To send DOMDocument or non processed data file it is set to false
success: function(data)   // A function to be called if request succeeds
{
alert(data);
}
});
}));

</script>
</head>
<body>
<div class="main">
<h1>Ajax Image Upload</h1><br/>
<hr>
<form id="uploadimage" action="" method="post" enctype="multipart/form-data">
<div id="image_preview"><img id="previewing" src="noimage.png" /></div>
<hr id="line">
<div id="selectImage">
<label>Select Your Image</label><br/>
<input type="file" name="file" id="file" required />
<input type="submit" value="Upload" class="submit" />
</div>
</form>
</div>
</body>
</html>


来源:https://stackoverflow.com/questions/28121129/upload-files-with-ajax-and-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!