angular.js 和 Spring MVC 之文件上传的兼容

本文介绍如何使用AngularJS结合SpringMVC实现单文件和多文件上传功能,包括前端页面设置、AngularJS文件读取及发送请求、后端SpringMVC控制器处理等关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

由于公司用的angular.js和SSM实现前后端分离,前端是以angular.js+Bootstrap编写,而为了兼容Spring MVC中用使用MultipartFile接收文件的写法,查找了很多资料,使这种写法能够正确使用,以下是使用的框架版本,可能会存在影响

 

  1. angular.js:1.4.7
  2. Spring MVC:4.1.4

 

1.angular.js和Spring MVC单文件上传

1.HTML

<input type="file" id="upload">

2.angular.js

function(index) {
	var file = document.querySelector("#upload").files[0]
	var fd = new FormData();
	fd.append('file_id',$scope.arealist[index].file_id)
	fd.append('location',$scope.arealist[index].location)
	fd.append('file', file);
	$http({
		method : 'POST',
		url : '/i/zone/updateZone',
		data : fd,
		transformRequest : angular.identity,
		headers : {
			'Content-Type' : undefined
		}
	}).success(function(data) {
		console.log(data)
	});
};

这里要注意几点

  1. 使用id去获取文件,当使用$scope绑定的model获取文件时会失败,上传单文件要写下标[0]
  2. 请求必须为post,get无效,Controller中也要用post接收

3.Spring MVC

@RequestMapping(value = "/updateZone",method = RequestMethod.POST)
@ResponseBody
public Object updateZone(@RequestParam(value = "file_id", required = false) Integer file_id,
		@RequestParam(value = "location", required = false) String location,
		@RequestParam(value = "file", required = false) MultipartFile file) throws IOException {
	//执行相应的操作
	System.out.println(file.getOriginalFilename());
}

 

这里需要注意的是

  1. 用js中存入fd的相应的name去获取值和文件(这里写的比较繁琐,可以尝试使用实体去接收,但是name要和实体类属性对应,文件还是单独接收)

 

2.angular.js和Spring MVC多文件上传

仅需要修改HTML、angular、spring MVC部分代码,即可完成多文件上传功能

1.HTML

<input name="file" file-model="file" type="file" id="upload" multiple="multiple">

 

2.angular.js

function(){
	var files = document.querySelector("#upload").files
	var fd = new FormData();
	for(var i=0; i<files.length; i++){
		fd.append('files', files[i]);
	}
	fd.append("projectID" , $scope.projectID)
	fd.append("zoneID" , $scope.AreaID)
	fd.append("pointType" , pointType)
	$http({
		method : 'POST',
		url : '/i/point/addPoint',
		data : fd,
		transformRequest : angular.identity,
		headers : {
			'Content-Type' : undefined
		}
	}).success(function(data) {
		console.log(data)
	}
});

 

3.Spring MVC

@RequestMapping(value = "/updateZone",method = RequestMethod.POST)
@ResponseBody
public Object addPoint(@RequestParam(value = "file_id", required = false) Integer file_id,
		@RequestParam(value = "location", required = false) String location,
		@RequestParam(value = "files", required = false) MultipartFile[] files) throws IOException {
	//执行相应的操作
	for (MultipartFile file: files) {
		System.out.println(file.getOriginalFilename());
	}
}

PS:欢迎补充更好的方法和指出其中的不足

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值