H5前端上傳文件的幾個解決方案


目前,幾個項目中用到了不同的方法,總結一下分享出來。

第一種,通過FormData來實現。

首先,添加input控件file。

<input type="file" name="uploadFile1" id="uploadFile1" runat="server" value="" multiple accept="image/jpg,image/jpeg,image/png,image/bmp,video/*"/>

然后添加對應的前端代碼。

var input = document.getElementById("uploadFile");

    var getOnloadFunc = function (aImg) {
        return function (evt) {
            aImg.src = evt.target.result;
        };
    }
    input.addEventListener("change", function (evt) {
        for (var i = 0, numFiles = this.files.length; i < numFiles; i++) {
            var file = this.files[i];

            var img = document.createElement("img");
            $(".tp").append(img);

            var reader = new FileReader();
            reader.onload = getOnloadFunc(img);
            reader.readAsDataURL(file);

            alert(file.name);

            var fd = new FormData();
            // 直接傳遞file對象到后台
       fd.append(
"image", file); fd.append("guanId", $("input[name=commonGuanId]").val()); $.ajax({ url : '/tools/submit_ajax.ashx?action=sign_upload', type : 'POST', data : fd, processData: false, contentType: false, timeout : 10000, success : function(data) { var mydata = JSON.parse(data); if (mydata.status == 1) { alert("上傳成功"); } else { alert("失敗,請稍后重試!"); } }, error : function(xhr,textStatus){ //alert('上傳失敗,請稍后重試'); } }); } }, false);

第二個,微信JSSDK接口,這個用起來比較方便,但是必須在微信的環境中應用,有局限性。

 1  wx.config({
 2         debug: false,
 3         appId: '<% = config.appId%>',
 4         timestamp: '<% = config.timestamp%>',
 5         nonceStr: '<% = config.nonceStr%>',
 6         signature: '<% = config.signature%>',
 7         jsApiList: ['chooseImage',
 8             'previewImage',
 9             'uploadImage',
10             'downloadImage'
11         ]
12     });
13 
14 
15     var serverIds = ""
16     function uploadImg() { 
17         if(serverIds!="")
18         {
19             serverIds="";
20         }
21         wx.chooseImage({
22             count: 1,
23             sizeType: ['original', 'compressed'], // 可以指定是原圖還是壓縮圖,默認二者都有  
24             sourceType: ['album', 'camera'],      // 可以指定來源是相冊還是相機,默認二者都有  
25             success: function (res) {
26                 var localIds = res.localIds;      // 返回選定照片的本地ID列表  
27                 syncUpload(localIds);             // localId可作為img標簽的src屬性顯示圖片  
28             }
29         });
30     }
31 
32     function syncUpload(localIds) {
33         var localId = localIds.pop();
34         wx.uploadImage({
35             localId: localId,                // 需要上傳的圖片的本地ID,由chooseImage接口獲得  
36             isShowProgressTips: 1,           // 默認為1,顯示進度提示  
37             success: function (res) {
38                 var serverId = res.serverId; // 返回圖片的服務器端serverId  
39                 serverIds = serverIds + serverId + ",";
40 
41                 if (localIds.length > 0) {
42                     syncUpload(localIds);
43                 } else {
44                     $.ajax({
45                         type: "POST",
46                         url: "/tools/submit_ajax.ashx?action=img_upload",
47                         dataType: "json",
48                         data: {
49                             "serverIds":serverIds
50                         },
51                         timeout: 20000,
52                         success: function (data, textStatus) {
53                             if(data.status==1){
54                                 $("#picname").attr("src", data.msg);
55                                 $("#hidImgUrl").attr("value",data.msg);
56                             }else{
57                                 alert(data.msg);
58                             }
59                         },
60                         error:function(data){
61                             alert("系統錯誤,請刷新頁面重試!");
62                         }
63                     });
64                 }
65             }
66         });
67     };

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM