gpt4 book ai didi

angularjs 和 spring mvc - 在一个请求中上传多个文件

转载 作者:行者123 更新时间:2023-12-03 08:20:21 25 4
gpt4 key购买 nike

我想在我的 Web 应用程序中实现文件上传,我正在使用 angular.js在客户端和 spring mvc在服务器端。

我设法使用 https://github.com/danialfarid/angular-file-upload 使单个文件上传和多个文件上传工作正常工作.问题是,当我上传多个文件时,每个文件都会作为单独的请求发送给我(这是阅读示例代码后的明显事件):

//inject angular file upload directives and service.
angular.module('myApp', ['angularFileUpload']);

var MyCtrl = [ '$scope', '$upload', function($scope, $upload) {
$scope.onFileSelect = function($files) {
//$files: an array of files selected, each file has name, size, and type.
for (var i = 0; i < $files.length; i++) {
var $file = $files[i];
$scope.upload = $upload.upload({
url: 'server/upload/url', //upload.php script, node.js route, or servlet url
// method: POST or PUT,
// headers: {'headerKey': 'headerValue'}, withCredential: true,
data: {myObj: $scope.myModelObj},
file: $file,
//(optional) set 'Content-Desposition' formData name for file
//fileFormDataName: myFile,
progress: function(evt) {
console.log('percent: ' + parseInt(100.0 * evt.loaded / evt.total));
}
}).success(function(data, status, headers, config) {
// file is uploaded successfully
console.log(data);
})
//.error(...).then(...);
}
}
}];

所有文件都有一个迭代。

现在我想知道是否有可能以某种方式将多个文件作为一个单一的请求上传。

最佳答案

在 Spring Controller 端创建

@RequestMapping(value = "/upload", method = RequestMethod.POST)
public String save(@ModelAttribute("filesForm") FileUploadForm filesForm) {
List<MultipartFile> files = filesForm.getFiles();
//do something

}


public class FileUploadForm
{
private List<MultipartFile> files;

// geters and setters ...

}

在客户端上传服务
return {
send: function(files) {
var data = new FormData(),
xhr = new XMLHttpRequest();
xhr.onloadstart = function() {
console.log('Factory: upload started: ', file.name);
$rootScope.$emit('upload:loadstart', xhr);
};

xhr.onerror = function(e) {
$rootScope.$emit('upload:error', e);
};
xhr.onreadystatechange = function(e)
{
if (xhr.readyState === 4 && xhr.status === 201)
{
$rootScope.$emit('upload:succes',e, xhr, file.name ,file.type);

}
};

angular.forEach(files, function(f) {
data.append('files', f, f.name);
});

xhr.open('POST', '../upload');
xhr.send(data);


}
};

关于angularjs 和 spring mvc - 在一个请求中上传多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19989495/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com