自定义图片点击, 上传文件

前端之家收集整理的这篇文章主要介绍了自定义图片点击, 上传文件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

本文是用angularjs框架和$resource组件实现的,不过原理都是大同小异
注意重点: 设置请求的Content-Type头为undefined.
Angularjs 对于post和put请求,默认的Content-Type是application/json,w我们需要改变它的值. 通过设置Content-Type为undefined,浏览器会设置Content-Type为multipart/form-data,并且会自动填充正确的分界(boundary).
手动设定Content-Type为multipart/form-data,会导致请求的分界参数填充失败.

可以参考这个链接
http://www.jb51.cc/article/p-umvewndx-qu.html

html

 <!--添加图片--> @H_403_15@<div style="margin-top: 2rem;"> @H_403_15@<div style="padding: 1rem 0;">@H_403_15@<p>添加图片@H_403_15@</p>@H_403_15@</div> @H_403_15@<div style="display: flex; justify-content: flex-start; align-items: flex-start; flex-wrap: wrap; height: 14rem;"> @H_403_15@<div class="images_upload" ng-repeat="image in uploadedImages track by $index" ng-click="removeImage(image)" style="background-image: url({{image}}@H_403_15@); "> @H_403_15@</div> @H_403_15@<div class="images_upload" onclick="document.getElementById('uploadImage').click()" ng-if="uploadedImages.length< 8" style="background-image: url(img/orders/jh@2x.png); background-size: inherit;"> @H_403_15@</div> @H_403_15@<input id="uploadImage" type="file" accept="image/*" multiple="true" style="display: none;"> @H_403_15@</div> @H_403_15@</div>

js_controller

var isUploading = false;
    //选取图片绑定时事件
    var uploadedButton = document.getElementById('uploadImage');
    uploadedButton.onchange = function() {
      //发请求
      isUploading = true;
      var formData = new FormData();
      for(var index=0; index<uploadedButton.files.length; index++)
      {
        if (index+$scope.uploadedImages.length >= 8)
        {
          break;
        }
        formData.append('file',uploadedButton.files[index]);
      }

      //接口上传
      buyerOrderService.uploadPictures(formData).then(
        function(data) {
          isUploading = false;
          utilsService.console_info(data,'图片返回数据:');

          if (!data || !data instanceof Array)
          {
            utilsService.console_error(data,'图片返回数据不规格;');
            return;
          }
          //页面展示
          for(var index=0; index<data.length; index++)
          {
            $scope.uploadedImages.push(data[index].data);
          }
        },function(error) {
          isUploading = false;
          utilsService.alert({template: '<a>图片上传失败,请稍后尝试</a>'})
        });
    };

    //删除图片
    $scope.removeImage = function(imageUrl) {
      $scope.uploadedImages.splice($scope.uploadedImages.indexOf(imageUrl),1);
    };

js_service

//resource的配置: 
      uploadPictures: {
        url: requestUrl + '/upload/batch.do',/*/upload.do*/
        isArray: true,method: 'POST',//这个很重要,必须加上
        headers: {'Content-Type': undefined}
      }

   /** * 上传图片 */
    service.uploadPictures = function(params)
    {
      return resource.uploadPictures(params).$promise;
    };

猜你在找的Angularjs相关文章