我想使用角度js和弹簧启动来上传文件。
这是我的java控制器
//upload Files
@RequestMapping(value="/upload",headers=("content-type=multipart/*"), method=RequestMethod.POST)
public @ResponseBody String handleFileUpload(@RequestParam("name") String name,@RequestParam("file") MultipartFile file){
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
BufferedOutputStream stream =
new BufferedOutputStream(new FileOutputStream(new File(name)));
stream.write(bytes);
stream.close();
return "You successfully uploaded " + name + "!";
} catch (Exception e) {
return "You failed to upload " + name + " => " + e.getMessage();
}
} else {
return "You failed to upload " + name + " because the file was empty.";
}
}
这是我的表格
<section id="contact-info">
<section id="contact-page">
<div class="container">
<div class="center">
<p class="lead">Import reports</p>
</div>
<div class="row contact-wrap">
<div class="status alert alert-success" style="display: none"></div>
<form id="main-contact-form" class="contact-form" name="contact-form" method="POST" enctype="multipart/form-data" >
<div class="col-sm-5 col-sm-offset-1">
<div class="form-group">
<label>name *</label>
<input type="text" name="name" class="form-control" required="required" ng-model="rap.name">
</div>
<div class="form-group">
<label>file</label>
<input type="file" name="file" class="form-control" ng-model="rap.file">
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary btn-lg" ng-click="upload()">Import File</button>
</div>
</form>
</div><!--/.row-->
</div><!--/.container-->
</section><!--/#contact-page-->
这是我的js控制器
//Upload files
$scope.upload=function(rap){
$http.post('http://localhost:8080/upload?name='+$scope.rap.name+"file="+$scope.rap.file ,{
headers: { 'Content-Type': undefined },
transformRequest: angular.identity })
.success(function(){
console.log('Post Succeded !');
})
.error(function(){
console.log('Post Failed .');
});
}
当我填写表格并点击ImportFile时,我有下面提到的错误。有什么想法吗?
答案 0 :(得分:0)
$http.post('http://localhost:8080/uploadname='+$scope.rap.name+"file="+$scope.rap.file ,{
headers: { 'Content-Type': undefined },
transformRequest: angular.identity })
这个方法的签名有点不对 - 第二个对象是数据, 请参阅https://docs.angularjs.org/api/ng/service/ $ http#post
"file="+$scope.rap.file
您是否尝试通过url将文件内容作为multipart对象发布?通常文件发布在http正文中。
此外,ngModel不支持绑定输入[file]的值,并非所有浏览器都支持javascript中的FileAPI - 请参阅例如https://github.com/angular/angular.js/issues/1375
所以,如果你需要支持&#34;遗产&#34;浏览器,请使用为此目的编写的第三方ng polyfill库(如@Uzi Kilon建议的那样)。
如果您对现代浏览器没问题,可以添加自定义输入[file] onchange处理程序,将文件绑定到模型并正确发布到服务器端点。(参见AngularJS: how to implement a simple file upload with multipart form?)