[英]How to upload files with 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 的棘手業務,但絕對不是不可能的。 幾件事情要注意。
下面我正在編寫用於將單個文件提交到服務器的示例代碼。
<--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.