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     };

 

posted on 2017-09-10 12:27  郑陆伟  阅读(2639)  评论(0编辑  收藏  举报

导航