springMVC下ajax上传文件

功能描述
点击文件上传框,选中图片时,页面显示选择的图片
需要用ajax将选中的文件发送到后台,后台将文件上传到项目里面,再返回一个图片相对路径

1.前端页面

	<p>
			<img src="${news.img }" id="displayImg"/>
			图片:<input type="file" name = "fimg" id="fileToUpload"/>
	</p>

2.脚本

<script type="text/javascript">
$(function(){
	//文件上传框值改变时触发
	$("#fileToUpload").change(function(){
		var upLoadFile = new FormData();//好像是要封装成form类型数据
		upLoadFile.append("fimg", $("#fileToUpload")[0].files[0]);//将jquery对象转成dom对象
		$.ajax({
			url:"news/alterImgPath.do",
			dataType:"json",
			type:"POST",
			data:upLoadFile,
			//mimeType:"multipart/form-data",
			contentType: false, //不设置内容类型 ,好像是必须的
			processData: false,//不处理数据,好像是必须的
			success:function(map){
				$("#displayImg").attr("src", map.msg);
			},
			error:function(){
				alert("ajax failed");
			}
		});
	})
})
</script>

3 . 后台service层:写了一个上传文件的方法

public String alterImgPath(CommonsMultipartFile fimg) {
		String imgPath = null;
		if (fimg.getSize() > 0) {
			String oldName = fimg.getOriginalFilename();
			String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."));
			File newFile = new File("D:/tools/apache-tomcat-8.0.50/webapps/img/" + newName);
			try {
				fimg.transferTo(newFile);
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			imgPath = "../img/" + newName;
		}
		return imgPath;
	}

4.controller层

/*
* @ResponseBody: 返回的结果直接响应给页面,不经过视图解析器什么什么的
* 传过来的文件 必须通过注解@RequestParam绑定 
*/
@RequestMapping("/alterImgPath.do")
	@ResponseBody
	public Map<String, String> alterImgPath(@RequestParam(value="fimg")CommonsMultipartFile fimg){
		Map<String, String> map = new HashMap<String, String>();
		String path = fs.alterImgPath(fimg);
		map.put("msg", path);
		return map;
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值