How to upload file using pure vanilla javascript and php?

前端 未结 1 1845
闹比i
闹比i 2020-12-20 21:33

I have an existing html form which uploads a file to the server as soon as the user selects an image file.

I have done something like this.

//html c         


        
相关标签:
1条回答
  • 2020-12-20 22:12

    You are using FormData which works very much the same way a normal form does.

    First of all, in PHP files will not be in $_POST but instead in $_FILES, see the documentation.

    What that documentation does mention, along with the $_FILES buffer, is that you need to use the multipart/form-data encoding, any FormData transferred through an XMLHttpRequest will have this set by default, though you may want to check it if the $_FILES remain empty. You should remove the xhr.setRequestHeader("Content-type","image"); and let the XHR object handle it, of - if that doesn't work - add

    xhr.setRequestHeader("Content-type","multipart/form-data");
    

    There is a pretty nice example right here at stackoverflow

    0 讨论(0)
提交回复
热议问题