提交Ajax请求文件上传通过JavaScript [英] Submit ajax request with file upload via JavaScript

查看:97
本文介绍了提交Ajax请求文件上传通过JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可以通过提交表单form.submit()和响应是正确的。现在我想用ajax提交,但我有一个问题提交文件时。

I have a form that can be submitted via form.submit() and the response is correct. Now I want to submit it using ajax, but I have a problem when submitting a file.

的形式为pretty的简单:

The form is pretty simple:

<form name="Upload" enctype="multipart/form-data" method="post" action="upload.asp">
    <input type="file" name="file" id="fileinput"/>
    <input type="button" name="FileUpload" class="button" id="append_new" 
    onclick="xmlhttpPost('upload.asp', document.getElementById('fileinput').files[0]);" value="submit file"/>
</form>

我得到了Ajax调用如下:

I got the ajax call as following:

function xmlhttpPost(strURL, form) {
    var xmlHttpReq = false;
    var self = this;
    // Mozilla/Safari
    if (window.XMLHttpRequest) {
        self.xmlHttpReq = new XMLHttpRequest();
    }
    // IE
    else if (window.ActiveXObject) {
        self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
    }
    self.xmlHttpReq.open('POST', strURL, true);
    self.xmlHttpReq.setRequestHeader('Content-Type', 'multipart/form-data');
    self.xmlHttpReq.onreadystatechange = function() {
        if (self.xmlHttpReq.readyState == 4) {
            updatepage(self.xmlHttpReq.responseText);
        }
    }
    self.xmlHttpReq.send('file=' + file);
}

function updatepage(str){
    document.getElementById("fileitems").innerHTML = str;
}

现在的问题是:在服务器获取字符串 [目标文件] ,而不是实际的文件内容。我怎样才能确保文件数据提交?

The problem now is: the server gets the string [object file] rather than the actual file content. How can I make sure file data is submitted?

推荐答案

您可以使用的 FORMDATA 为:

function xmlhttpPost(strURL, form) {
    var xmlHttpReq = false;
    var self = this;
    // Mozilla/Safari
    if (window.XMLHttpRequest) {
        self.xmlHttpReq = new XMLHttpRequest();
    }
    // IE
    else if (window.ActiveXObject) {
        self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
    }
    self.xmlHttpReq.open('POST', strURL, true);
    self.xmlHttpReq.setRequestHeader('Content-Type', 'multipart/form-data');
    self.xmlHttpReq.onreadystatechange = function () {
        if (self.xmlHttpReq.readyState == 4) {
            updatepage(self.xmlHttpReq.responseText);
        }
    }
    if ( !! window.FormData) {
        var formData = new FormData();
        formData.append('file', form);
        self.xmlHttpReq.send(formData);
    }
}

function updatepage(str) {
    document.getElementById("fileitems").innerHTML = str;
}

这里的 一个完整的AJAX文件上传与进步的一个不错的例子。

Here's a decent example of a full ajax file uploader with progress.

这篇关于提交Ajax请求文件上传通过JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆