使用PUT上传AngularJS图像,可能,怎么样?

时间:2014-07-17 14:08:20

标签: javascript angularjs

我试图使用AngularJS上传带有PUT或Post请求的图像,这是可能的,如果是这样,如下所示如何不更改标题(仍然是json)并且没有有效负载。

这就是我的尝试:

在我的控制器中:

       $scope.uploadFile = function (elm) {

            $scope.files = elm.files
            $scope.$apply();

            var fd = new FormData()
            fd.append('file', $scope.files[0])


            $scope.profile

                .customPOST(fd, "", ["Content-Type", undefined])
             .withHttpConfig({
                    transformRequest: angular.identity
                });

            event.preventDefault();


        };

HTML:

<input type="file" name="file" onchange="angular.element(this).scope().uploadFile(this.files)"/>

此代码实际上获取文件名并将其添加到数据库中,但在put请求期间实际上没有文件上传。

5 个答案:

答案 0 :(得分:1)

这是我喜欢用于文件上传的指令:
https://github.com/danialfarid/angular-file-upload

您可以使用凉亭安装它:bower install ng-file-upload --save
它具有许多功能,如进度条处理和轻松拖放。

您可以在github链接上找到有关如何使用它的示例,但是我在Coffeescript中使用AWS S3直接上传的方式如何。请注意,上传到s3需要更多的代码。这还包括从服务器生成令牌。 那就是你在那里看到的/api/media/upload_token

$scope.processUpload = (metadata) ->
  $scope.fileUploads.push metadata
  $http.put('/api/media/' + metadata._id, metadata)
  .success (res) ->
    // do your stuff here when the upload is finished
    // $scope.reloadMedia();
  console.log metadata


$scope.onFileSelect = ($files) ->
  # merge new uploads, ignore old uploads
  $scope.files = $files;
  $scope.upload = [];
  # create a new closure for each file upload
  for file, i in $files
    file.progress = parseInt 0
    do (file, i) ->
      anticache = Math.random().toString(36).substring(3,9)
      $http.get('/api/media/upload_token?mimeType=' + file.type + '&rnd=' + anticache,
      {filename: file.name})
      .success (response) ->
        s3Params = response
        uploadData =
          url: 'https://<mybucketname>.s3.amazonaws.com/'
          method: 'POST'
          data:
            key: s3Params.filename + '$$' + file.name
            acl: 'public-read'
            'Content-Type': file.type
            AWSAccessKeyId: s3Params.AWSAccessKeyId
            success_action_status: 201
            Policy: s3Params.s3Policy
            Signature: s3Params.s3Signature
          file: file

        # start the upload
        $scope.upload[i] = $upload.upload(uploadData)
        .progress (evt) ->
          file.progress = parseInt(100.0 * evt.loaded / evt.total)
        .success (res, status, headers, config) ->
          file.progress = parseInt 100
          if status is 201
            xmlDoc = (new DOMParser).parseFromString(res, 'application/xml')
            getXmlValue = (k) -> xmlDoc.getElementsByTagName(k)[0].firstChild.nodeValue
            metadata =
              _id: response.filename
              location: getXmlValue 'Location'
              bucket: getXmlValue 'Bucket'
              key: getXmlValue 'Key'
              etag: getXmlValue 'ETag'
              filename: file.name
            $scope.processUpload(metadata)
          else
            throw new Error("File Upload Failed! Server status is not 201");
            alert 'Upload Failed, please try again.'

这是我的Jade视图,请注意我所拥有的课程来自Bootstrap

.form-group.well(ng-file-drop='onFileSelect($files)')
  span.btn.btn-primary.btn-file.btn-block
    | Upload Media
    input(type='file', ng-file-select='onFileSelect($files)', multiple)
  p.help-block You can also drag and drop files here.
  .row(ng-repeat='file in files')
    .col-md-8
      .progress
        .progress-bar(role='progressbar', style='width:{{file.progress}}%;')
            | {{file.name}} : {{file.progress}}
    .col-md-4
      button.btn.btn-warning(type='button', ng-click='abort($index)', ng-show='file.progress != 100') Abort
  div(ng-file-drop-available='dropSupported=true', ng-show='!dropSupported') HTML5 Drop File is not supported!

答案 1 :(得分:1)

为了使用AngularJS上传图像,您可以将输入标记放在表单中并提交表单。

因此在HTML中,您的代码应如下所示:

<form id='uploadForm' enctype='multipart/form-data' method = 'post' name ='settingForm'>
    <input id='inputFile' type='file' name = 'uploadFile' />
    <button id='saveSetting' ng-click='onSubmit()' name='save'>Save</button>
</form>

在这里你可以注意到enctype设置为multipart,方法为post。

在控制器中:

$scope.onSubmit = function() {
    var options = {
        target: '',
        url: '<your server url>',
        success: function() {
            //what ever you require on success
        }
    };
    $('#uploadForm').ajaxSubmit(options);
}

在服务器中,您可以在请求参数中获取文件(在NodeJS中,它将如下所示):

req.files.uploadFile;

其中&#39; uploadFile&#39;是您在HTML标记中指定的名称

希望有所帮助!!

答案 2 :(得分:1)

您可以使用这样的角度方法, HTML部分,

<input type="file" ng-file-select="onFileSelect($files)" />

在你的控制器中写下这个,

    $scope.onFileSelect = function ($files) {
        var file = $files[0];
        // upload file to server
        $scope.upload = $upload.upload({
            url: 'http://www.yourdomain.com/yourpath',
            file: file
        }).success(function(data, status, headers, config) {
            // file is uploaded successfully
        }).error(function (data) {
            // file upload failed
        });
    };

答案 3 :(得分:0)

您可以尝试这种方式:

HTML部分:

<input type="file" name="file" onchange="angular.element(this).scope().uploadFile(this.files)"/>

角度部分:

$scope.uploadFile = function(files) {
    var fd = new FormData();

    fd.append("file", files[0]);

    $http.post(uploadUrl, fd, {
        withCredentials: true,
        headers: {'Content-Type': undefined },
        transformRequest: angular.identity
    }).success( /*COOOOOOLLL*/ ).error( /*Use the force Luke!*/ );

};

或者,如果您想添加一些进度条,可以尝试使用多个文件上传:

<div ng-controller="FileUploadCtrl">
  <input type="file" ng-file-select="onFileSelect($files)" multiple>
</div>

angular.module('myApp', ['angularFileUpload']);

var FileUploadCtrl = [ '$scope', '$upload', function($scope, $upload) {
  $scope.onFileSelect = function($files) {
    for (var i = 0; i < $files.length; i++) {
      var file = $files[i];
      $scope.upload = $upload.upload({
        url: 'server/upload/url', 
        data: {uploadObject: $scope.myModelObj},
        file: file,
      }).progress(function(evt) {
        console.log('percent: ' + parseInt(100.0 * evt.loaded / evt.total));
      }).success(function(data, status, headers, config) {
        console.log(data);
      });
    }
  };
}];

答案 4 :(得分:0)

以下为我工作,因为我正在寻找将文件发布到Amazon S3的解决方案。使用PUTPOST作为方法

$http({
    method: 'PUT',
    url: http://www.yourdomain.com/yourpath',
    data: file,
    headers: {
        'Content-Type': undefined
    },
    transformRequest : function (data, headersGetter) {
        return data;
    }
});