首页 > 代码库 > 上传文件或者图片到服务器端

上传文件或者图片到服务器端

html部分:

<input type="file" accept="image/png,image/jpeg"   ng-model="img"  id="img" />

js部分:

 1 $scope.postFile = function(data, url) {
 2         var deferred = $q.defer();
 3         $http({
 4                 url: url,
 5                 data: data,
 6                 method: "post",
 7                 transformRequest : angular.identity,
 8                 headers: {
 9                      ‘Content-Type‘ : undefined//设置为undefined,会自动识别问formdata
10                 },
11                 eventHandlers: {
12                     progress: function(c) {
13                             console.log(‘total -> ‘ + c.total+"loaded" + c.loaded);
14                             console.log(c);
15                         }
16                 },
17                 uploadEventHandlers: {//查看进度
18                     progress: function(e) {
19                          if(e.lengthComputable) {
20                               var percentComplete = e.loaded / e.total;
21                               console.log("上传进度"+(percentComplete*100)+"%");
22                          }else {
23                              console.log("error!");
24                          }
25                     }
26                 }
27             })
28             .then(
29                 function(response) {
30                     deferred.resolve(response.data);
31                 },
32                 function(response) {
33                     deferred.reject(response);
34                 }
35             );
36         return deferred.promise;
37     }
38     //预览图片
39     $scope.preview = function() {
40         var ewm_preview = document.getElementById(‘img‘).files[0];
41         if(window.FileReader) {
42             var fr = new FileReader();
43             fr.onload = function(evt) {
44                 $scope.ewm_pre_url = evt.target.result;
45                 $(‘.preview_img‘).attr(‘src‘,evt.target.result);//预览图片元素
46             }
47             fr.readAsDataURL(ewm_preview);
48         }
49     }
50     $scope.ewm_update_param = {
51         "name":"",
52         "type":"",
53         "file":document.getElementById(‘img‘).files[0]
54     }
55     var formdata = http://www.mamicode.com/new FormData();
56         for(var key in $scope.ewm_update_param) {
57             formdata.append(key,$scope.ewm_update_param[key])
58         }
59     
60     $scope.postFile(formdata,‘/api/app/qrcode/upload‘).then(function(res) {
61         if(res.msg=="成功" && res.content.url) {
62             $scope.ewm_url = res.content.url+"&_=" + Date.now();//加时间戳,解决缓存问题
63         }
64     })

其中input的accept等属性请参照:http://www.haorooms.com/post/input_file_leixing 

上传文件或者图片到服务器端