简体   繁体   English

如何使用 FormData 和 XmlHTTPRequest 上传文件?

[英]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:我在您的代码中发现了两个问题:

  1. In JavaScript code, you explicitly defined the "Content-Type" as "multipart/form-data".在 JavaScript 代码中,您明确地将“Content-Type”定义为“multipart/form-data”。 JS automatically gets the content type when you make the XHR Request.当您发出 XHR 请求时,JS 会自动获取内容类型。
  2. In the 4th line of your PHP code, the key of the $_FILE is "file".在 PHP 代码的第 4 行中,$_FILE 的键是“file”。 You need to change it to "myfile", in order to make it work.您需要将其更改为“myfile”,以使其正常工作。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM