我有一个输入类型=“文件”如下:
<input id="identityDocument" name="identityDocument" ng-model="candidature.identityDocument"
ui-jq="filestyle" type="file" class="filestyle input-lg"
file-model="uploadIdentityDocument"
ui-options="{
buttonText: '{{'ACTIONS.UPLOAD' | translate}}',
iconName: 'fa fa-inbox'
}"
accept="image/*" valid-file required>
让我在范围内知道这个输入文件我使用这个指令:
.directive('fileModel',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]);
});
});
}
};
});
所以我想在提交此表单时将文件上传到其中,如下所示:
let file = $scope.uploadIdentityDocument;
let fd = new FormData();
fd.append('file', file);
$http.post('http://localhost:8080/fileUpload', fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
})
.error(function(){
});
在服务器端这是我的休息服务:
@RestController
public class UploadService {
@Autowired
IUploadMetier uploadMetier;
@RequestMapping(value="/fileUpload", method = RequestMethod.POST)
public ResponseEntity<String> UploadFile(MultipartHttpServletRequest request) {
String response = uploadMetier.uploadFile(request);
if(response.equals("false")){
return new ResponseEntity<>("There was an error uploading this file: " + response + " to the server :-(", HttpStatus.INTERNAL_SERVER_ERROR);
}else{
return new ResponseEntity<>("The file: " + response + " has uploaded successfully :-)", HttpStatus.OK);
}
}
}
这是上传文件的功能:
public String uploadFile(MultipartHttpServletRequest request) {
Iterator<String> itr=request.getFileNames();
MultipartFile file=request.getFile(itr.next());
String fileName=file.getOriginalFilename();
File dir = new File("\\MyPath");
if (dir.isDirectory())
{
File serverFile = new File(dir,fileName);
BufferedOutputStream stream = null;
try {
stream = new BufferedOutputStream(
new FileOutputStream(serverFile));
stream.write(file.getBytes());
stream.close();
} catch (IOException e) {
e.printStackTrace();
return "false";
}
}else {
return "false";
}
return fileName;
}
然后我收到此错误消息:
java.util.NoSuchElementException: null
at java.util.LinkedHashMap$LinkedHashIterator.nextNode(LinkedHashMap.java:713) ~[na:1.8.0_73]
at java.util.LinkedHashMap$LinkedKeyIterator.next(LinkedHashMap.java:734) ~[na:1.8.0_73]
at org.capvalue.fme.metier.mpl.UploadMetierImpl.uploadFile(UploadMetierImpl.java:19) ~[classes/:na]
at org.capvalue.fme.web.rest.UploadService.UploadFile(UploadService.java:23)
行UploadMetierImpl.java:19
指的是:MultipartFile file=request.getFile(itr.next());
我该如何解决这个问题?
我刚注意到,当我在console.log $scope.uploadIdentityDocument
时,我得到了未定义,我不知道为什么我会这样做!
答案 0 :(得分:0)
错误是没有定义$ scope.identityDocUpload,解决方案是删除我使用的fileModel指令并将其添加到我的输入中:
onchange="angular.element(this).scope().setFile(this,'identityDocumentUpload')"
setFile
功能:
$scope.setFile = function(element, name) {
$parse(name).assign($scope, element.files[0]);
}