如何使用AJAX上传文件

时间:2015-07-07 01:59:50

标签: javascript ajax html5 file-upload

我想使用AJAX上传。

这是我的HTML代码

<form id="upload-form" enctype="multipart/form-data" method="post" action="upload">
    File Name:<input type="text" name="name" /><br />
    <input type="file" name="file" /><br />
    <input type="submit" />
</form>

这是我的Javascript代码:

var file = document.querySelector("[type=file]").files[0], 
    reader = new FileReader; 

reader.onload = function(e){
    var xhr = new XMLHttpRequest
    xhr.open("POST", document.querySelector("form#upload-form").action, true);

    //set payload
    var boundary = '------multipartformboundary' + (new Date).getTime().toString(16);
    var dashdash = '--';
    var crlf = '\r\n';

    var payload = '';
    payload += boundary;
    payload += crlf;

    payload += 'Content-Disposition: form-data; name="file"';
    payload += crlf;    

    payload += 'Content-Type: ' + file.type;
    if (file.fileName) {
        payload += '; filename="' + file.name + '"';
    }
    payload += crlf + crlf;

    payload += reader.result;
    payload += crlf;


    payload += boundary;
    payload += crlf;
    payload += 'Content-Disposition: form-data; name="name"';
    payload += crlf + crlf;
    payload += document.querySelector("[name=name]").value || ""
    payload += crlf;

    payload += boundary;
    payload += dashdash;

    xhr.setRequestHeader('Content-type', 'multipart/form-data; boundary=' + boundary)
    xhr.send(payload)
}
reader.readAsBinaryString(file)

请求的有效负载如下:

------multipartformboundary14e6631b3eb
Content-Disposition: form-data; name="file"
Content-Type: image/png

PNG


(some binary code)
------multipartformboundary14e6631b3eb
Content-Disposition: form-data; name="name"

My test file
------multipartformboundary14e6631b3eb--

但是,请求状态为 400

描述说&#34;客户端发送的请求在语法上是不正确的。&#34; (服务器是Servlet + Tomcat 8)

当我只提交没有AJAX的表单时,它可以成功上传。因此,我不认为这是服务器的问题。

2 个答案:

答案 0 :(得分:0)

在内容类型行中:

xhr.setRequestHeader('Content-type', 'multipart/form-data; boundary=' + boundary)

您的代码提供:

multipart/form-data; boundary=------xxxxxxxxx

但是,它应该是:

multipart/form-data; boundary=----xxxxxxxxx

注意短划线的数量。

所以改成它:

xhr.setRequestHeader('Content-type', 'multipart/form-data; boundary=' + boundary.substr(2))

再试一次。

答案 1 :(得分:0)

                var Self = this;
                    Self.xhr = new XMLHttpRequest();
                    Self.url = "./connect.php"; // your file to post data
                    Self.xhr.open("POST",Self.url,true);
                    Self.xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                    Self.xhr.onreadystatechange = function() {
                    if(Self.xhr.readyState == 4 && Self.xhr.status == 200) {
                    Self.return_data = Self.xhr.responseText.trim();

                    }
              Self.xhr.send(Self.logData);

这是我使用XHR请求将数据发布到我的服务器的方式。和connect.php将更新我的数据库。因此,您可以在发出XHR请求之前添加需要发送到“Self.logData”的数据。并且你需要一个像connect.php或其他一些文件来处理服务器端的帖子数据