将上传的图像发送到服务器并保存在服务器上。

8

我想上传一张图片并将其保存到服务器上。我已经成功上传了该图片并获得了预览,但卡在了将该图片发送到服务器的步骤。我想使用Angular服务将此图像发送到服务器。

以下是HTML代码:

<input type="file" fileread="vm.uploadme" />
<img src="{{vm.uploadme}}" width="100" height="50" alt="Image preview...">

这是一个指令。
(function(){
    angular.module('appBuilderApp').directive("fileread", [function () {
        return {
            scope: {
                fileread: "="
            },
            link: function (scope, element, attributes) {
                element.bind("change", function (changeEvent) {
                    var reader = new FileReader();
                    reader.onload = function (loadEvent) {
                        scope.$apply(function () {
                            scope.fileread = loadEvent.target.result;
                        });
                    }
                    reader.readAsDataURL(changeEvent.target.files[0]);
                });
            }
        }
    }]);
})();

你能展示一下你目前完成的工作吗? - putvande
这是我的指令,用于获取图像文件。app.directive("fileread", [function () { return { scope: { fileread: "=" }, link: function (scope, element, attributes) { element.bind("change", function (changeEvent) { var reader = new FileReader(); reader.onload = function (loadEvent) { scope.$apply(function () { scope.fileread = loadEvent.target.result; reader.readAsDataURL(changeEvent.target.files[0]); - shamila
请把这个放到你的问题里面,好吗? - putvande
@shamilasallay 后端需要什么?多部分可能吗?让我知道,这样我就可以给你一个答案。 - Christos Baziotis
1
在这里,您将找到适用于所有类型服务器的上传器:http://ngmodules.org/modules?query=file+upload - Joao Polo
@adithya,你试过我的答案了吗?有帮到你吗?如果是,请接受我的答案。 - Christos Baziotis
1个回答

14

假设在后端你需要使用Multipart,这是一段对我有效的代码。

还有一个jsfiddle供参考。

var app = angular.module('myApp', [])

app.controller('MyController',

  function MyController($scope, $http) {

    //the image
    $scope.uploadme;

    $scope.uploadImage = function() {
      var fd = new FormData();
      var imgBlob = dataURItoBlob($scope.uploadme);
      fd.append('file', imgBlob);
      $http.post(
          'imageURL',
          fd, {
            transformRequest: angular.identity,
            headers: {
              'Content-Type': undefined
            }
          }
        )
        .success(function(response) {
          console.log('success', response);
        })
        .error(function(response) {
          console.log('error', response);
        });
    }


    //you need this function to convert the dataURI
    function dataURItoBlob(dataURI) {
      var binary = atob(dataURI.split(',')[1]);
      var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
      var array = [];
      for (var i = 0; i < binary.length; i++) {
        array.push(binary.charCodeAt(i));
      }
      return new Blob([new Uint8Array(array)], {
        type: mimeString
      });
    }

  });


//your directive
app.directive("fileread", [
  function() {
    return {
      scope: {
        fileread: "="
      },
      link: function(scope, element, attributes) {
        element.bind("change", function(changeEvent) {
          var reader = new FileReader();
          reader.onload = function(loadEvent) {
            scope.$apply(function() {
              scope.fileread = loadEvent.target.result;
            });
          }
          reader.readAsDataURL(changeEvent.target.files[0]);
        });
      }
    }
  }
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
  <div ng-controller="MyController">
    <input type="file" fileread="uploadme" />
    <img src="{{uploadme}}" width="100" height="50" alt="Image preview...">
    <br/>
    <p>
      Image dataURI:
      <pre>{{uploadme}}</pre>
    </p>
    <br/>
    <button ng-click="uploadImage()">upload image</button>
  </div>
</div>

请注意:以下部分:

{
    transformRequest: angular.identity,
    headers: {
        'Content-Type': undefined
    }
}

这是一些 Angular 的魔法,为了让 $http 解析 FormData 并找到正确的内容类型等等...


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接