gpt4 book ai didi

javascript - XMLHttpRequest发送图像文件

转载 作者:行者123 更新时间:2023-12-04 02:16:22 25 4
gpt4 key购买 nike

我想将文件发送到服务器并在那里进行处理,然后发送响应。
要发送文件,我使用了 FormData()的方法,看起来一切正常,文件已发送,但是无法用 $ _FILES解析 +仅通过可见内容php:// input

  • 为什么在 $ _FILES 中看不到文件?
  • 如何解析?
  • FormData()是否在所有浏览器中都有效?

  • 我的代码:

    HTML
    <form id="myform">
    <input type="file" name="filename">
    <input type="button" name="button" value="Send">
    </form>

    JS
    var form = document.forms.myform;
    form.elements.button.onclick = function(){
    var file = form.elements.filename.files[0];
    if(file){
    img(file);
    }else{
    alert("Not file.");
    }
    };
    function img(file){
    var formdata = new FormData();
    formdata.append('file', file);

    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'img.php');
    xhr.setRequestHeader('Content-Type', 'multipart/form-data');
    xhr.send(formdata);
    xhr.onreadystatechange = function(){
    if(xhr.readyState != 4) return;
    if(xhr.status != 200){
    alert("Status: " + xhr.status);
    }else{
    alert(xhr.responseText);
    }
    };
    }

    PHP
    <?php
    error_reporting(-1);
    print_r($_FILES['file']['size']); // only example, doesn't work

    $content = file_get_contents('php://input');
    print_r($content); // it's work , result in the photo
    ?>

    Photo

    最佳答案

    1.为什么在$ _FILES中看不到文件?

    因为没有必要使用编码。

    2.如何解析?

    具有全局变量$ _FILES

    3. FormData()是否可在所有浏览器中使用?

    编号Browser compatibility

    关于javascript - XMLHttpRequest发送图像文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38561578/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com