SprinMVC实现文件上传(源码亲测)

关于文件上传的记录:
1:自定义file文件样式:

<input type=file id=browsefile style=“visibility:hidden” οnchange=filepath.value=this.value>



2。选择图片上,将图片写入到指定目录,传路径到数据库。
出于个人习惯 前段采用angularjs
$scope.uploadFile=function(){
EmpService.uploadFile().success(
function(response){
if(response.flag){
alert(response.message);
}
else{
alert(response.message);
}
});
}

this.uploadFile = function(){
		// 向后台传递数据:
		var formData = new FormData();
		// 向formData中添加数据:
		formData.append("file",file.files[0]);
		return $http({
			method:'post',
			url:'../emp/uploadFile.do',
			data:formData,
			headers:{'Content-Type':undefined} ,// Content-Type : text/html  text/plain
			transformRequest: angular.identity
		});
	}
```angular默认采用json格式传输,因此此处必须设置undefined

``` 前端不用多说了,主要看后台:
@RequestMapping("/uploadFile")
	public Result fileUpload(MultipartFile file) throws Exception, IOException{
		//示例图片上传
		String fileName=file.getOriginalFilename();
		
		//修改唯一文件名
		int endIndex=fileName.lastIndexOf('.');	
		String newFileName=UUID.randomUUID().toString()+fileName.substring(0, endIndex);
		String end=fileName.substring(endIndex);
		//指定文件上传目录
		File filePath=new File("E:/upload/img/"+newFileName+end);
		System.out.println(filePath);
		//如果文件夹不存在,则创建文件夹
		if(!filePath.exists())
		{
			filePath.mkdir();
		}
		//写如磁盘
		file.transferTo(filePath);
		
		//将文件路径存到数据库
		String empImg="E:/upload/img"+newFileName+end;
		empService.uploadFile(empImg);
		
		return new Result(true, "ok");
	}
注意:这里的**MultipartFile file**  得和AjAx里面的formData.append("file",file.files[0]);字段对应。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值