[英]How do I upload a file using FormData and XmlHTTPRequest?
I'm trying to send a file from a web page to a php script using FormData, and the file isn't showing up in the $_FILES
variable in the PHP page.我正在尝试使用 FormData 将文件从网页发送到 php 脚本,但该文件未显示在 PHP 页面的
$_FILES
变量中。 Not sure if my error is on the JS side or the PHP side, or if I'm misunderstanding something deeper about the process.不确定我的错误是在 JS 方面还是在 PHP 方面,或者我是否对这个过程有更深层次的误解。
Here's my code:这是我的代码:
function uploadFile() { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState === XMLHttpRequest.DONE) { if (xhr.status === 200) { console.log('success'); } else { console.log('error'); } } }; xhr.open('POST','php/parsefile.php',true); xhr.setRequestHeader("Content-Type","multipart/form-data"); var formData = new FormData(); formData.append("myfile", document.querySelector('#fileInput').files[0]); xhr.send(formData); }
<input type="file" id="fileInput"> <button onclick="uploadFile();">Upload</button>
Here's parsefile.php
:这是
parsefile.php
:
<?php
echo("Error: " . $_FILES["myfile"]['error'] . "\n");
echo("Name: " . $_FILES['file']['name'] . "\n");
When I upload a simple, small (64 bytes) text file, the console reads success
, but the response from the server is just this:当我上传一个简单的小(64 字节)文本文件时,控制台读取
success
,但服务器的响应如下:
Error:
Name:
What am I missing here?我在这里缺少什么? Thanks for any help anyone can provide.
感谢任何人可以提供的任何帮助。
I found two issues in your code:我在您的代码中发现了两个问题:
You can check my edited code below:您可以在下面查看我编辑的代码:
JS Code: JS代码:
function uploadFile() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
console.log('success');
} else {
console.log('error');
}
}
};
xhr.open('POST','php/parsefile.php',true);
var formData = new FormData();
formData.append("myfile", document.querySelector('#fileInput').files[0]);
xhr.send(formData);
}
PHP Code: PHP代码:
<?php
echo "Name: ". $_FILES['myfile']['name'];
echo "Error: ".$_FILES['myfile']['error'];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.