[英]Upload file asynchronously with Angular, ng-file-upload using a RESTful API
I have a form and a few of that form fields are file uploads. 我有一个表单,其中一些表单字段是文件上传。 This is what I have:
这就是我所拥有的:
Now, this is what I want to do: 现在,这就是我想要做的:
¿How can I perform this files upload programatically? ¿如何以编程方式执行此文件上传? (I'm using angular promises, so no problem with sequential requests...)
(我使用的是角度承诺,因此顺序请求没有问题...)
Here is my code: 这是我的代码:
$scope.upload = function (files, url) {
if (files && files.length) {
for (var i = 0; i < files.length; i++) {
var file = files[i];
Upload.upload({
url: url,
//fields: {'username': $scope.username},
file: file
}).progress(function (evt) {
var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
console.log('progress: ' + progressPercentage + '% ' + evt.config.file.name);
}).success(function (data, status, headers, config) {
console.log('file ' + config.file.name + 'uploaded. Response: ' + data);
});
}
}
};
My html: 我的html:
<input type="file" class="btn btn-danger" ng-file-select ng-model="files" ng-multiple="multiple"> Doit!
<input class="btn btn-danger" ng-file-select ng-model="files" ng-multiple="multiple">Doit too!
Ok, so I finally got this. 好的,所以我终于明白了。
I did this: 我这样做:
So the trick here is to execute two requests, one to create the entity and retrieve the id, the second, to just upload the file. 因此,这里的技巧是执行两个请求,一个请求创建实体并检索ID,第二个请求只是上传文件。
The code looks like this: 代码如下:
// This is called every time the user selects a file
$scope.selectedFile = function (files, doc) {
if (doc === 'resumee') $scope.documents.resumee = files.pop();
else if (doc === 'dni') $scope.documents.dni = files.pop();
else if (doc === 'picture') $scope.documents.picture = files.pop();
};
// This is called when the user submits the form
$scope.upload = function (docname, url) {
var file = $scope.stepThree.documents[docname];
return Upload.upload({
url: url,
method: 'POST',
headers: {'Content-Type': file.type},
fileFormDataName: docname,
data: file,
file: file
}).progress(function (evt) {
var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
console.log('progress: ' + progressPercentage + '% ' + evt.config.file.name);
});
};
And finally, the markup is this: 最后,标记是这样的:
<div class="form-horizontal">
<div class="form-group">
<div class="col-sm-2">
<label> Resumen Curricular </label>
</div>
<div class="col-sm-2">
<button class="btn btn-danger" ngf-select ngf-change="selectFile($files, 'resumee')"> Seleccione</button>
<p>{{stepThree.documents.resumee.name}}</p>
</div>
</div>
</div>
Since no one commented on this approach/technique, I'll take this as the best way in the world to work with file uploads, angular and a REST API. 由于没有人评论这种方法/技术,因此我将其作为处理文件上传,Angular和REST API的最佳方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.