1.1 前端页面HTML代码示例
1.文件上传
文件上传一般包括前端页面的文件选择、文件上传、后台接收文件、保存文件等步骤。
1.1 前端页面HTML代码示例
<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="file"/>
<input type="submit" value="上传"/>
</form>
1.2 后台Controller代码示例
@Controller
public class FileUploadController {
@RequestMapping(value="/upload", method=RequestMethod.POST)
public String handleFileUpload(@RequestParam("file") MultipartFile file, HttpServletRequest request){
try {
String fileName = file.getOriginalFilename();
String path = request.getSession().getServletContext().getRealPath("/upload/" + fileName);
// 保存文件
file.transferTo(new File(path));
request.setAttribute("msg", "文件上传成功!");
} catch (Exception e) {
request.setAttribute("msg", "文件上传失败!");
}
return "fileupload";
}
}
其中,@RequestParam("file")注解表示接收名字为file的文件,@RequestMapping(value="/upload", method=RequestMethod.POST)表示请求url为/upload,请求方法为POST。
1.3 文件上传结果展示HTML代码示例
<div style="text-align:center">
<!-- 如果msg不为空,即为上传失败,添加红色字体颜色 -->
<p style="${empty msg? 'color:#FF0011': ''}">${msg}</p>
<img src="upload/${file.name}" alt="no image"/>
<p>上传文件名字:${file.name}</p>
<p>上传文件大小:${file.size}</p>
</div>
其中,${}表示引用传参进来的数据,upload/${file.name}表示文件上传之后保存的路径。
2.文件下载
文件下载与文件上传不同,文件下载只能从后台进行处理。一般包含前端页面的选择文件、请求后台数据、后台返回数据等步骤。
2.1 前端页面HTML代码示例
<a href="download?file=example.txt">下载文件</a>
其中,download?file=example.txt表示请求url,file表示后台根据该字段获取文件。
2.2 后台Controller代码示例
@Controller
public class FileDownloadController {
@RequestMapping("/download")
public ResponseEntity<byte[]> fileDownload(HttpServletRequest request) throws Exception{
// 获取文件名,根据文件名从磁盘获取文件
String fileName = request.getParameter("file");
String downLoadPath = request.getSession().getServletContext().getRealPath("/upload/" + fileName);
FileInputStream inputStream = new FileInputStream(new File(downLoadPath));
// 将文件返回
byte[] bytes = new byte[inputStream.available()];
inputStream.read(bytes);
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
httpHeaders.setContentDispositionFormData("attachment", new String(fileName.getBytes("UTF-8"), "ISO-8859-1"));
ResponseEntity<byte[]> responseEntity = new ResponseEntity<byte[]>(bytes, httpHeaders, HttpStatus.OK);
inputStream.close();
return responseEntity;
}
}
其中,@RequestMapping("/download")表示请求url为/download。
2.3 文件下载结果展示HTML代码示例
文件下载在后台即可完成,无需前端页面展示。
以上即为SpringMVC实现文件上传与下载的完整攻略。
本文标题为:SpringMVC实现文件上传与下载
基础教程推荐
- java – SLF4J是否可以在多线程应用程序中用于记录到数据库? 2023-10-30
- MyBatisPlus代码生成器的原理及实现详解 2023-03-30
- SpringBoot如何使用Undertow做服务器 2023-02-19
- Java基础夯实之线程问题全面解析 2023-07-01
- JSP中的字符替换函数 str_replace() 实现! 2023-12-06
- MyBatis图文并茂讲解注解开发一对一查询 2023-02-18
- Java OpenCV图像处理之图形与文字绘制 2022-11-03
- spring aop Pointcut execution规则介绍 2023-08-11
- springboot实战权限管理功能图文步骤附含源码 2023-01-18
- java中String.intern()方法功能介绍 2022-12-02
