XMLHttpRequest Level 2 FormData 提交二进制文件

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/

    原文作者:小渝人儿
    原文地址: https://segmentfault.com/a/1190000002399216
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞