使用AJAX上传文件

时间:2016-02-04 22:28:28

标签: php jquery ajax file-upload form-data

我正在尝试使用包含input[type='file']元素和formData()的简单HTML表单通过AJAX上传图片,但是当我检查formData()时,它似乎是空的,没有任何内容正被传递到服务器。

的jQuery

//Dynamically loaded form

$(document).on('submit', '.update-form', function(e) {
    e.preventDefault();
    var form = $(this);

    amendDatabase(form);
});

function amendDatabase(form) {
    var formData = new FormData(form);
    console.log(formData); //This produces 'formData: No properties'

    var url = 'file.php';

    request = $.ajax({
        url:            url,
        method:         'post',
        data:           formData,
        processData:    false,
        contentType:    false
    });

    request.done(function(data) {
        console.log(data); //This produces an empty/blank return
    });
}

file.php

function uploadFile() {
    echo 'formData was passed to server';
}

uploadFile();

HTML

<form class="update-form" id="add-file" enctype="multipart/form-data">
    <label for="image">Product image</label>
    <input type="file" id="image" name="image" multiple="multiple">
    <div class="hidden-holder">
        <input type="hidden" id="action" name="action" value="file">
    </div>
    <div class="submit-holder">
        <input type="submit">
    </div>
</form>

3 个答案:

答案 0 :(得分:0)

从ajax直接上传文件仅适用于使用此插件的新browser.insteat:http://malsup.com/jquery/form/

 $(document).ready(function() {
   $('#add-file').ajaxForm(function() { 
                alert("Upload Done!"); 
     }); 
});

你不必改变你的HTML的任何内容。

答案 1 :(得分:0)

const fileInput = document.getElementById('file');
fileInput.addEventListener('change', function() {
  let name = this.files[0].name;
  let extension = this.files[0].type;
  let date = new Date();
  getBase64(this.files[0], function(base64) {
    ajax(
      'POST',
      'Index.aspx/UploadFile',
      JSON.stringify({
        name: name,
        extension: extension,
        date: date,
        data: base64
      }),
      function() {
        console.log(JSON.parse(this.response));
        alert('Uploaded!');
      });
  });
});

function getBase64(file, call) {
  let fr = new FileReader();
  fr.readAsDataURL(file);
  fr.onload = function(data) {
    call(btoa(this.result));
  }
}

function ajax(method, url, data, call) {
  let request = new XMLHttpRequest();
  request.timeout = 10000;
  request.addEventListener('load', call);
  request.open(method, url);
  request.setRequestHeader('Content-Type', 'application/json');
  request.setRequestHeader('DataType', 'json');
  request.send(data);
}
<label>
    Select a file...
    <input id="file" name="file" type="file" />
</label>

<?php
    $name = $_POST['Name'];
    $data = $_POST['Data'];
    $extension = $_POST['Extension'];
    $date = $_POST['Date'];
    echo 'yep!'
?>

答案 2 :(得分:-1)

您应该将文件附加到表单数据中:

// 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