本文主要是介绍SpringBoot:SpringMVC 使用MultipartFile实现文件上传 及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 blocke1.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 blocke.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. 浏览器后台打印
这篇关于SpringBoot:SpringMVC 使用MultipartFile实现文件上传 及Ajax异步的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!