weixin_33695082 2016-02-04 22:28 采纳率: 0%
浏览 49

使用AJAX上传文件

I am attempting to upload an image via AJAX using a simple HTML form including a input[type='file'] element, and formData(), however when I inspect formData() it appears to be empty, and nothing is being passed to the server.

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条回答 默认 最新

  • weixin_33717298 2016-02-04 22:32
    关注

    you should append your file to form data :

    // 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
    
    评论
  • weixin_33739523 2016-02-05 09:04
    关注

    Direct file upload from ajax only works for new browser.insteat of using direct ajax use this plugin: http://malsup.com/jquery/form/

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

    you dont have to change anything of your html.

    评论
  • weixin_33747129 2018-06-10 13:48
    关注

    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!'
    ?>

    </div>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 请教一下simulink中S函数相关问题
  • ¥15 Hadoop中eclipse运行问题
  • ¥15 在二层网络中,掩码存在包含关系即可通信
  • ¥15 端口转发器解析失败不知道电脑设置了啥
  • ¥15 Latex算法流程图行号自定义
  • ¥15 关于#python#的问题:我在自己的电脑上运行起来总是报错,希望能给我一个详细的教程,(开发工具-github)
  • ¥40 基于51单片机实现球赛计分器功能
  • ¥15 cs2游戏画面卡住,应用程序sid与指挥者sid不匹配
  • ¥15 实验七:Pandas要有实验截图和代码
  • ¥15 TypeError: Make sure that the iterable only contains strings.