JSLite.io 使用FormData ajax上传文件

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

上传文件例子

原生写法

html<form id="form1" enctype="multipart/form-data" method="post" action="/session/sendImg?subID=3&subsID=2&ssID=163">
    <input type="file" name="file" id="file"/>
    <input type="text" name="name" id="name"/>
    <input type="button" onclick="sendForm()" value="Upload" />
</form>
jsfunction sendForm(){
    var fr = document.getElementById("form1")
    var fd = new FormData(fr);//使用HTML表单来初始化一个FormData对象
    fd.append("file", document.getElementById('file').files[0]);

    var xhr = new window.XMLHttpRequest();
    xhr.upload.addEventListener("progress", uploadProgress, false);
    xhr.addEventListener("load", uploadComplete, false);
    xhr.addEventListener("error", uploadFailed, false);
    xhr.addEventListener("abort", uploadCanceled, false);
    console.log(fd)
    xhr.open("POST", "/session/sendImg?subID=3&subsID=2&ssID=163");
    xhr.send(fd);
}
//+ uploadComplete  上传结束函数  
//+ uploadFailed    上传错误函数  
//+ uploadCanceled  终止函数   

JSLite 方法

使用JSLite来发送FormData,但必须要正确的设置相关选项(jQuery是一样的玩儿)

jsfunction sendForm(){
    var fd = new FormData();
    fd.append("file",$('#file')[0].files[0]);
    fd.append("name",$('#name').val());
    $.ajax({
        type:'POST',
        dataType:'text',
        processData: false,  // 告诉JSLite不要去处理发送的数据
        contentType: false,   // 告诉JSLite不要去设置Content-Type请求头
        data:fd,
        url:'/session/sendImg?subID=3&subsID=2&ssID=163',
        success:function(data){
           console.log('success:',data)
        },
        error:function(d){
           console.log('error:',d)
        }
    })
}

append()

给当前FormData对象添加一个键/值对
void append(DOMString name, Blob value, optional DOMString filename);
void append(DOMString name, DOMString value);
MDN 参考地址

浏览器兼容性

FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support7+4.0 (2.0)10+12+5+
支持filename参数 (Yes)22.0(22.0)???
    原文作者:小弟调调
    原文地址: https://segmentfault.com/a/1190000002548247
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞