SpringBoot:SpringMVC文件上传及Ajax异步

一、使用Spring框架中的MultipartFile实现后台代码逻辑处理

1. MultipartFile API 如下:

在这里插入图片描述

2. 后台逻辑代码

@Controller
public class FileUploadController {
	
	//文件上传
	@ResponseBody
	@RequestMapping(value="/fileUpload",method=RequestMethod.POST)
	public String fileUpload(@RequestParam("file")MultipartFile multFile,HttpServletRequest request) {
		//获取上传文件名并打印
		String multFileName = multFile.getOriginalFilename();
		System.out.println("文件名为:"+multFileName);
		//获取上传文件大小并打印
		long size = multFile.getSize();
		System.out.println("文件大小:"+size);
		
		//*. 更改文件名:命名规则+时间
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss-SS");
		String times = simpleDateFormat.format(new Date());
		 //获取文件后缀
		String suffix = multFileName.substring(multFileName.lastIndexOf("."));
		System.out.println("文件后缀名"+suffix);
		
		//**. 文件内容读取
		try {
			InputStream inputStream = multFile.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"GBK");
			char[] chars = new char[1024];
			int len = inputStreamReader.read(chars);
			String context = new String(chars,0,len);
			System.out.println("文本内容是:"+context);
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		
		//***. 文件上传(主要)
		String path = "E:/FileUpload";
		File newFile = new File(path+"/"+times+suffix);
		if(!newFile.getParentFile().exists()) { //判断文件父目录是否存在
			newFile.getParentFile().mkdirs();
		}
		
		try {
			multFile.transferTo(newFile);
		} catch (IllegalStateException | IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return "上传成功";
	}
	
	//首页
	@RequestMapping("/")
	public String toIndex() {
		
		return "index";
	}

}

二、前端代码

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>文件上传下载测试</title>
	<script src="${request.contextPath}/js/jquery-1.12.4.min.js"></script>
</head>
<body>
<div style="width: 100%;margin: 0 20% ;display: flex; flex-direction: column; width: 200px; ">
	<h1>文件上传</h1>
	<form id="uploadForm" action="${request.contextPath}/fileUpload" method="POST" enctype="multipart/form-data">
		<input id="file" type="file" name="file"/>
		<input type="text" name="text1" />
		<input type="text" name="text2" />
		<div style="margin-top: 10px;">
			<input type="submit" value="直接上传"/>
			<button type="button" id="ajaxBtn">ajax后台上传</button>
		</div>
	</form>
	
	<h1>文件下载</h1>
	
	<script type="text/javascript">
		$("#ajaxBtn").on('click',function(){
			console.log("ajaj异步文件上传开始---");
			//使用 HTML5 FormData对象; 使用js原生对象
			var formData = new FormData($("#uploadForm")[0]);
			$.ajax({
				url:'${request.contextPath}/fileUpload' ,
				type:'POST',
				data:formData ,
				cache: false ,
				contentType:false ,
				processData:false ,
				success:function(data){
					console.log("ajax返回值"+data);
				}
			});
		});
			
		
	</script>
</div>
</body>
</html>

三、打印结果

1. eclipse控制台打印

在这里插入图片描述

2. 浏览器后台打印

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/StarryaSky/article/details/84729164