我有一个使用AngularJs的工作多部分文件上传实现,它将文件发送到其他控制器以存储文件。
HTML
<form name="myForm" id="loginForm" data-ng-submit="submitForm()">
<input type="text" name="user_fullname" ng-model="fullName">
<input type="text" name="Contactnumber" ng-model="number"/>
<input type="file" data-ng-file-select data-ng-model="item.file" id="document" data-uploader="uploader" data-file-model="myFile" accept="application/pdf" class="form-control ng-pristine ng-valid"/>
<button class="btn btn-sm btn-warning" data-ng-click="addItem(item.file)" type="button"> Upload </button> <br>
<button id="submit" class="btn btn-success">Register</button>
</form>
JS
app.directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function(){
scope.$apply(function(){
modelSetter(scope, element[0].files[0]);
});
});
}
};
}]);
app.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file, uploadUrl){
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(data){
$scope.res=data;
})
.error(function(){
});
}
}]);
app.controller('detailsController',[ '$scope', '$http', 'fileUpload', function($scope, $http, fileUpload)
{
$scope.items = [];
$scope.item = {};
$scope.addItem = function (item)
{
if ($scope.item.file != undefined)
{
$scope.items.push( $scope.item);
$scope.item = {};
$scope.showTable=true;
}
else {
$('#myModalErr2').modal('show');
}
}
$scope.submit = function()
{
var formData =
{
fullName : $scope.fullName,
contactNumber: $scope.number,
};
$http.post('userdetails', formData ).success(function(response)
{
if ($scope.items.length > 0)
{
for (var i = 0 ; i < $scope.items.length ; i++)
{
$scope.uploadFile($scope.items[i]);
}
}
};
$scope.uploadFile = function(file){
var file = $scope.myFile;
var uploadUrl = 'upload';
fileUpload.uploadFileToUrl(file, uploadUrl);
};
REST控制器(用于文件上传)
@RequestMapping(value="/upload", method=RequestMethod.POST, consumes={"multipart/form-data"})
public @ResponseBody void handleFileUpload(MultipartHttpServletRequest request, HttpServletResponse response) {
Iterator<String> itr = request.getFileNames();
MultipartFile mpf = null;
while(itr.hasNext()){
System.out.println("Inside loop");
mpf = request.getFile(itr.next());
if(files.size() >= 10)
files.pop();
fileMeta = new Document();
fileMeta.setFileName(mpf.getOriginalFilename());
try {
fileMeta.setBytes(mpf.getBytes());
FileCopyUtils.copy(mpf.getBytes(), new FileOutputStream("D:/temp/files/"+mpf.getOriginalFilename()));
} catch (IOException e) {
e.printStackTrace();
}
files.add(fileMeta);
}
}
在角度控制器中,首先我将名称和联系人号码发布到REST,如果成功,则自动生成的ID将返回到我正在获取的角度。重点是,如何将此id与multipart文件一起发送以存储具有该特定id的文件?