AngularJS使用FormData API上传多个文件 [英] AngularJS Upload Multiple Files with FormData API

查看:139
本文介绍了AngularJS使用FormData API上传多个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用Laravel 5.1作为后端将图像和视频文件上传到Angular应用程序中的服务器.所有Ajax请求都需要首先发送到Laravel控制器,并且我们在这里有代码说明文件到达那里后如何处理.以前我们已经完成了普通的HTML表单以将文件上传提交到控制器,但是在这种情况下,我们需要避免刷新表单的页面,因此我尝试通过Angular在Ajax中进行此操作.

I need to upload image and video files to the server in an Angular application using Laravel 5.1 as the back end. All Ajax requests need to go to the Laravel controller first, and we have the code there for how the file gets handled when it gets there. We have previously done normal HTML forms to submit file uploads to the controller, but in this case we need to avoid the page refresh of a form, so I am attempting this in Ajax through Angular.

我需要将以前通过HTML表单发送到控制器的Ajax信息发送到Laravel控制器吗?

What information do I need to send to the Laravel controller with Ajax that was being sent to the controller via an HTML form previously?

这是Laravel控制器中用于处理文件信息的代码.这就是我需要弄清楚如何发送的内容,因此希望可以重用以下代码:

This is the code in the Laravel controller that handled the file information once it got there. That's what I need to figure out how to send, so I can hopefully reuse this code:

    $promotion = Promotion::find($id);
    if (Input::hasFile('img_path')){
        $path             = public_path().'/images/promotion/'.$id.'/';
        $file_path        = $path.'promotion.png';
        $delete           = File::delete($file_path);
        $file             = Input::file('img_path');
        $uploadSuccess    = $file->move($path, 'promotion.png');
        $promotion->img_path = '/images/promotion/'.$id.'/promotion.png';
    }
    if (Input::hasFile('video_path')){
        $path             = public_path().'/video/promotion/'.$id.'/';
        $file_path        = $path.'promotion.mp4';
        $delete           = File::delete($file_path);
        $file             = Input::file('video_path');
        $uploadSuccess    = $file->move($path, 'promotion.mp4');
        $promotion->video_path = '/video/promotion/'.$id.'/promotion.mp4';
    }

正如您在上面看到的那样,我们正在将获得的任何文件转换为文件名为promotion.png的PNG,以便轻松获取,并且我们仅接受.mp4视频格式.因此,我们不必担心检查文件是否存在以及是否可以覆盖它.这就是为什么您可以在代码中看到我们在保存之前删除了该名称的所有现有文件的原因.

As you can see above, we are converting whatever file we get to a PNG with the file name promotion.png so it's easy to fetch, and we are only accepting .mp4 video format. Because of that, we don't need to worry about checking if the file exists and is it ok to overwrite it. That's why you can see in the code we delete any existing file of that name before saving.

HTML只是带有文件"类型的输入:

The HTML was just an input with a type of "file:

<input type="file" id="img_path" name="img_path" class="promo-img-path" accept="image/*">

我们现在正在使用Angular,所以我不能再通过HTML表单发送以上内容.这就是我需要弄清楚的方法.

We are using Angular now so I can't just send the above through an HTML form anymore. That's what I need to figure out how to do.

我们是两个尽力而为的开发人员,因此,我相信有更好的方法可以做到这一点.但是,在重构这一切之前,我希望我可以使用Angular(或将jQuery作为最后的手段)向控制器发送Laravel为了使上述代码正常工作所需的任何文件数据.答案可能很简单,例如将PUT发送到上面那个控制器中的方法,但是可以使用这种格式的文件信息来代替普通的JSON有效负载,并且可以使用...来收集该信息".

We are two developers just doing our best, so I'm sure there is a better way of doing this. However before I refactor this whole thing, I'm hoping I can use Angular (or jQuery as a last resort) to just send the controller whatever file data Laravel needs in order to make the above code work. The answer may be as simple as "send a PUT to the method in that controller above, but instead of a normal JSON payload, use file info in this format and you can gather that info with..."

我也希望将来有更多关于更好的方法的提示.

I would also appreciate any tips on better ways I can do this in the future.

推荐答案

如何使用$ http服务发布FormData

在使用 FormData API 到POST文件并数据,请务必设置 Content-Type标头undefined.

How to POST FormData Using the $http Service

When using the FormData API to POST files and data, it is important to set the Content-Type header to undefined.

var fd = new FormData()
for (var i in $scope.files) {
    fd.append("fileToUpload", $scope.files[i]);
}
var config = {headers: {'Content-Type': undefined}};

var httpPromise = $http.post(url, fd, config);

默认情况下,AngularJS框架使用内容类型application/json.通过设置Content-Type: undefined,AngularJS框架将省略内容类型标头,从而允许 XHR API 设置内容类型.发送 FormData对象时,XHR API会设置内容键入具有适当边界和 base64 编码的multipart/form-data.

By default the AngularJS framework uses content type application/json. By setting Content-Type: undefined, the AngularJS framework omits the content type header allowing the XHR API to set the content type. When sending a FormData object, the XHR API sets the content type to multipart/form-data with the proper boundaries and base64 encoding.

有关更多信息,请参见 MDN Web API参考-XHR发送方法

For more information, see MDN Web API Reference - XHR Send method

您是如何将文件信息放入$scope.files的?

如何启用<input type="file">ng-model一起使用

此伪指令还使<input type="file">能够自动使用ng-changeng-form伪指令.

How to enable <input type="file"> to work with ng-model

This directive also enables <input type="file"> to automatically work with the ng-change and ng-form directives.

angular.module("app",[]);

angular.module("app").directive("selectFilesNg", function() {
  return {
    require: "ngModel",
    link: function postLink(scope,elem,attrs,ngModel) {
      elem.on("change", function(e) {
        var files = elem[0].files;
        ngModel.$setViewValue(files);
      })
    }
  }
});

<script src="//unpkg.com/angular/angular.js"></script>
  <body ng-app="app">
    <h1>AngularJS Input `type=file` Demo</h1>
    
    <input type="file" select-files-ng ng-model="fileArray" multiple>

    <code><table ng-show="fileArray.length">
    <tr><td>Name</td><td>Date</td><td>Size</td><td>Type</td><tr>
    <tr ng-repeat="file in fileArray">
      <td>{{file.name}}</td>
      <td>{{file.lastModified | date  : 'MMMdd,yyyy'}}</td>
      <td>{{file.size}}</td>
      <td>{{file.type}}</td>
    </tr>
    </table></code>
    
  </body>

使用multi-part/form-data发布二进制文件效率不高,因为 base64编码会增加33 % 高架.如果服务器API接受带有二进制数据的POST,请直接发布文件.

Posting binary files with multi-part/form-data is inefficient as the base64 encoding adds an extra 33% overhead. If the server API accepts POSTs with binary data, post the file directly.

请参见如何使用AngularJS(带有DEMO)

这篇关于AngularJS使用FormData API上传多个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆