2

XMLHttpRequest Level 2添加了一个新的接口FormData.利用FormData对象,我们可以通过JavaScript用一些键值对来模拟一系列表单控件,我们还可以使用XMLHttpRequest的send()方法来异步的提交这个"表单".比起普通的ajax,使用FormData的最大优点就是我们可以异步上传一个二进制文件.

想要更详细的了解如何使用FormData对象, 请查看使用FormData对象.

实例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ajax submit file</title>
</head>
<body>
<form enctype="multipart/form-data" method="post" name="fileinfo"> 
    <label>Your email address:</label> 
    <input type="email" autocomplete="on" autofocus name="userid" placeholder="email" required size="32" maxlength="64" /><br /> 
    <label>Custom file label:</label> 
    <input type="text" name="filelabel" size="12" maxlength="32" /><br /> 
    <label>File to stash:</label> <input type="file" name="file" required /> 
</form>
<div id="output"></div> 
<a href="javascript:sendForm()">Stash the file!</a>

<script type="text/javascript" src="js/jquery-1.7.1.js"></script>
<script type="text/javascript">
function sendForm() { 
    var oOutput = document.getElementById("output");
    var oData = new FormData(document.forms.namedItem("fileinfo")); 

    oData.append("CustomField", "This is some extra data"); 
    var oReq = new XMLHttpRequest();
    oReq.open("POST", "stash.php", true); 

    oReq.onload = function(oEvent) { 
        if (oReq.status == 200) { 
            oOutput.innerHTML = "Uploaded!"; 
        } 
        else { 
            oOutput.innerHTML = "Error " + oReq.status + " occurred uploading your file.<br \/>"; 
        } 
    }; 
    oReq.send(oData); 
}

</script>

</body>
</html>

你还可以使用jQuery来发送FormData,但必须要正确的设置相关选项:

<a id="sendForm" href="javascript:;">Stash the file!</a>

$("#sendForm").click(function(){
    var fd = new FormData(document.forms.namedItem("fileinfo")); 
    var request = $.ajax({ 
        url: "test.json", 
        type: "POST", 
        data: fd, 
        processData: false,  // 告诉jQuery不要去处理发送的数据   contentType: false   // 告诉jQuery不要去设置Content-Type请求头 
    });

    request.done(function(json){
        console.log("a");
    });

    request.fail(function(){
        console.log("b");
    });

});

其他方法:
fileuploader插件:http://www.phpletter.com/DOWNLOAD/


小渝人儿
1.1k 声望849 粉丝

前端工程师