AngularJS:如何使用多部分形式实现简单的文件上传? [英] AngularJS: how to implement a simple file upload with multipart form?

查看:31
本文介绍了AngularJS:如何使用多部分形式实现简单的文件上传?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做一个从 AngularJS 到 node.js 服务器的简单多部分表单发布,表单的一部分应包含 JSON 对象,另一部分应包含图像,(我目前只发布带有 $resource 的 JSON 对象)

I want to do a simple multipart form post from AngularJS to a node.js server, the form should contain a JSON object in one part and an image in the other part, (I'm currently posting only the JSON object with $resource)

我想我应该从 input type="file" 开始,但后来发现 AngularJS 不能绑定到那个..

I figured I should start with input type="file", but then found out that AngularJS can't bind to that..

我能找到的所有示例都是用于包装 jQuery 插件以进行拖放降低.我想简单上传一个文件.

all the examples I can find are for wraping jQuery plugins for drag & drop. I want a simple upload of one file.

我是 AngularJS 的新手,对编写自己的指令一点也不舒服.

I'm new to AngularJS and don't feel comfortable at all with writing my own directives.

推荐答案

一个真正的工作解决方案,除了 angularjs 没有其他依赖项(使用 v.1.0.6 测试)

A real working solution with no other dependencies than angularjs (tested with v.1.0.6)

html

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

Angularjs (1.0.6) 不支持input-file"标签上的 ng-model 所以你必须以本地方式"传递所有(最终)选定的文件来自用户.

Angularjs (1.0.6) not support ng-model on "input-file" tags so you have to do it in a "native-way" that pass the all (eventually) selected files from the user.

控制器

$scope.uploadFile = function(files) {
    var fd = new FormData();
    //Take the first selected file
    fd.append("file", files[0]);

    $http.post(uploadUrl, fd, {
        withCredentials: true,
        headers: {'Content-Type': undefined },
        transformRequest: angular.identity
    }).success( ...all right!... ).error( ..damn!... );

};

很酷的部分是 undefined 内容类型和 transformRequest: angular.identity,它们使 $http 能够选择正确的内容类型"并管理处理多部分数据时所需的边界.

The cool part is the undefined content-type and the transformRequest: angular.identity that give at the $http the ability to choose the right "content-type" and manage the boundary needed when handling multipart data.

这篇关于AngularJS:如何使用多部分形式实现简单的文件上传?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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