ajax上传文件(以图片为例) SpringMVC

本文介绍了一个基于HTML5和jQuery的文件上传与实时预览功能实现方案,包括表单设置、图片预览、表单提交、后端处理及文件上传工具类等关键步骤。

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

1.首先写出一个表单,设置表单属性

<form id="tableForm" name="tableForm" enctype="multipart/form-data">
	<input style="margin-left: 10px;" type="file" id="img" name="img" class="form-control">
	<img id="imgShow" src="" width="250px" height="250px" onerror="javascript:this.src='<%=basePath%>/images/timg.jpg'">
</form>

tips:enctype="multipart/form-data" 必须有


2.为了更好的用户体验,我们可以显示出用户所选择的图片

/*图片上传预览*/
$("#img").on("change",function() {
	// Get a reference to the fileList
	var files = !!this.files ? this.files : [];
	// If no files were selected, or no FileReader support, return
	if (!files.length || !window.FileReader){ return; };
	// Only proceed if the selected file is an image
	if (/^image/.test(files[0].type)) {
	// Create a new instance of the FileReader
		var reader = new FileReader();
		// Read the local file as a DataURL
		reader.readAsDataURL(files[0]);
		// When loaded, set image data as background of div
		reader.onloadend = function() {
			$("#imgShow").prop("src",this.result );
		}
	}else{
		layer.alert('请选择正确的图片格式!');
		$("#img").val('');
		$("#imgShow").prop("src",'');
	}
});
tips:此段代码中用到$("#img").val('');用来在用户选择了错误图片类型时,清除文件上传框的内容,并且此处只能传递空的字符串‘’,无法传递值。


3.提交表单:

var formData = new FormData($("#tableForm")[0]);	//获取表单内容
$.ajax({
	url : contextPath + "/user/save",
	type : "POST",
	data : formData,
	cache : false,
	contentType : false,
	processData : false,
	success : function(data){
		alert("上传成功!");
	},
});

tips:此处获取表单内容的方法为html5内置,可以获取表单内的文件信息,故选用此方法。ajax方法中不能添加datatype:“json“属性。cache、contentType、processData属性需要有。可以在表单中添加附加数据:formData.append("name","hu");


4.后台接受文件:

@ResponseBody
@RequestMapping(value = "save", method = RequestMethod.POST)
public void save(@RequestParam(value = "img", required = false) MultipartFile file,HttpServletRequest request) {
	User user = new User();
	user.setName(request.getParameter("name"));
	if (file.getSize() != 0) {	//判断是否有文件
		user.setImg(FileUpload.upload(file, request)); // 使用工具类上传文件
	}
}
tips:文件特殊接收,且此时无法再用对象直接接收前台传来的数据,所以我们需要从request对象中获取。


5.文件上传(工具类):

public class FileUpload {
	public static String upload(MultipartFile file,HttpServletRequest request){
		String path = request.getSession().getServletContext().getRealPath("upload/img");	//图片存放文件夹
		String fileName=new String();	//放置的文件名
		String backName=new String();	//返回的文件所在相对路径以及文件名
		if(file==null){		//无文件上传
			fileName="";
		}else{
			try {
				fileName = file.getOriginalFilename();	//获取文件名称(可修改为时间戳)
				backName=fileName;	//设置文件返回名称(可自由配置)
				File targetFile = new File(path, fileName);	//放入文件
				if (!targetFile.exists()) {		//如果文件不存在
					targetFile.mkdirs();	//绘制文件
				}
				file.transferTo(targetFile);	//文件上传
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return backName;	//返回文件名称
	}
}

tips:推荐将文件名根据自己情况改为时间戳等形式,最好不要带有中文(此处为省时间,无转换)。





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值