簡體   English   中英

如何使用 ajax 上傳文件?

[英]How to upload files with ajax?

我有個問題。 我的英語很弱

我正在使用 PHP 打印$_FILES變量,沒有任何問題。

在此處輸入圖像描述

但是當我用 AJAX 發布它時,它不會被抓住

假設你有這個 function 用於 AJAX:

function sendRequest(type, url, callback, async, params) {
    if (async !== false) async = true;
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = callback;
    xhttp.open(type, url, async);
    xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhttp.send(params);
}

你稱之為

sendRequest("POST", "yourpage.php", function() {
    if (this.readyState === 4) {
        console.log(JSON.parse(this.responseText));
    }
} true);

如果這一切都設置好了,那么您需要服務器向瀏覽器提供 JSON 響應,例如

<?php

//yourpage.php

//...Some stuff
echo json_encode($_FILES);

請注意,以上只是幻想代碼,您需要實際上傳文件才能使所有這些有意義。

文件上傳是 Ajax 的棘手業務,但絕對不是不可能的。 幾件事情要注意。

  1. 使用 javascript 的新 FormData class 提交文件,因為它非常健壯。
  2. 確保表單的 enctype 是 multipart/form-data。

下面我正在編寫用於將單個文件提交到服務器的示例代碼。

    <--html-->
    <form id="the-form" action="/upload/path" enctype="multipart/form-data">
      <input name="file" type="file">
      <input type="submit" value="Upload" />
    </form>

    <--javascript-->
    var fileInput = document.getElementById('the-file');
    var file = fileInput.files[0];
    var form = document.getElementById('the-form');
    form.onsubmit = function() {
      var formData = new FormData(form);    
      formData.append('file', file);    
      var xhr = new XMLHttpRequest();
      // Add any event handlers here...
      xhr.open('POST', form.getAttribute('action'), true);
      xhr.send(formData);    
      return false; // To avoid actual submission of the form
    }

致謝: https://thoughtbot.com/blog/ridiculously-simple-ajax-uploads-with-formdata

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM