AJAX File Upload with XMLHttpRequest

前端 未结 3 954
深忆病人
深忆病人 2020-11-27 18:45

I know there are a lot of similar questions, but I still haven\'t found a solution for my problem. I\'m trying to upload a file with XMLHttpRequest, so I developed the code

3条回答
  •  春和景丽
    2020-11-27 19:12

    To avoid the post_max_size limitation problem... but also out of memory problems on both sides :

    On the client side

    • use PUT instead of POST :

      xhr.open("put", "upload.php", true);

    • add custom headers to specify original FileName and FileSize :

      xhr.setRequestHeader("X-File-Name", file.name);
      xhr.setRequestHeader("X-File-Size", file.size);

    • use the File object directly in your XHR send method :

      xhr.send(file);

      Please note that the File object can be obtained directly via the “files” property of your input[type=file] DOM object

    On the server side

    • read the custom headers via $_SERVER :

      $filename = $_SERVER['HTTP_X_FILE_NAME'];
      $filesize = $_SERVER['HTTP_X_FILE_SIZE'];

    • read file data using php://input :

      $in = fopen('php://input','r');

    You'll then be able to send very big files (1GB or more) without any limitation!!!

    This code works for FireFox 4+, Chrome 6+, IE10+

提交回复
热议问题