尝试从Angularjscontroller获取文件到Spring Controller以从角度上传excel文件并从spring控制器读取
这是AngularController代码
'use strict';
webapp.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]);
});
});
}
};
}]);
webapp.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': 'application/x-www-form-urlencoded'}
})
.success(function(fd){
alert(sucess+fd)
})
.error(function(fd){
alert(error+fd)
});
}
}]);
webapp.controller('bussinesscontroller', ['$scope', 'fileUpload', function($scope, fileUpload){
$scope.uploadFile = function(){
var file = $scope.myFile;
console.log('file is ' );
console.dir(file);
var uploadUrl = '/uploadsfiles';
fileUpload.uploadFileToUrl(file, uploadUrl);
};
}]);
这是弹簧控制器代码
@RequestMapping(value="/uploadsfiles",method=RequestMethod.POST)
@ResponseBody
public JSONObject getFile(@RequestParam("file") String file ){
JSONObject jsonObject=new JSONObject();
/*System.out.println("data= "+data);*/
System.out.println("hiii...");
return jsonObject;
}
这是HTML代码
<body>
<div ng-controller="bussinesscontroller">
<fieldset>
<!-- <form name="fileupload" novalidate> -->
<legend>Excel File upload</legend>
<input type="file" file-model="myFile"/>
<button ng-click="uploadFile()">upload</button>
</fieldset>
<!-- </form> -->
</div>
</body>
</html>
答案 0 :(得分:0)
嗨@rohit看起来我对Angular并不熟悉,但我对Spring有足够的了解,告诉你问题在于它的配置。首先,你必须在web.xml中声明一个过滤器,让我们知道你试图使用它的FileUpload功能的Spring MVC:
TOP 1
下一步是配置什么是字节数限制,如果你想这样做(我建议你将它用于安全性和性能问题)。在spring-servlet.xml中添加这个bean:
<filter>
<filter-name>springMultipartFilter</filter-name>
<filter-class>org.springframework.web.multipart.support.MultipartFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>springMultipartFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
最后将文件上载依赖项添加到Maven配置,或者如果不使用Maven则添加库:
<bean id="filterMultipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="1048576"/>
</bean>
现在,您需要在代码中执行的操作是使用multipart文件创建一个简单的表单bean:
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
现在将Controller配置为在GET方法中创建此表单对象,该方法在Angular中显示HTML表单,在触发提交按钮时接收此对象的另一个POST方法:
import org.springframework.web.multipart.MultipartFile;
public class MyAngularSpreadSheetForm {
private MultipartFile spreadSheetFile;
public MultipartFile getSpreadSheetFile() {
return spreadsheetFile;
}
public void setSpreadSheetFile(MultipartFile spreadsheetFile) {
this.spreadsheetFile = spreadsheetFile;
}
}