springmvc实现上传和下载
2023-09-11 14:15:07 时间
非常简单的小例子,注释的很清楚。话不多少,看代码
FileController.java
package com.imooc; import org.apache.commons.io.IOUtils; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.io.OutputStream; import java.util.Date; /** * Created by 敲代码的卡卡罗特 * on 2018/4/15 16:52. */ @RequestMapping("/file") @Controller public class FileController { private String folder="E://update"; @PostMapping public void upload(MultipartFile file) throws Exception { System.out.println(file.getName()); //file 就是你前台传过来的参数名字 System.out.println(file.getOriginalFilename()); //idea快捷键.txt 就是你文件的实际名字 System.out.println(file.getSize()); //文件的大小 //这里只是一个小demo,按理说应该截取传过来的后缀的,这里写死了。 File localFile = new File(folder, new Date().getTime() + ".txt"); //复制到这个文件中 file.transferTo(localFile); } @GetMapping("/{id}") public void download(@PathVariable String id, HttpServletRequest request, HttpServletResponse response) throws Exception { //这个是jdk1.7的新用法,把流写在try的括号里面,就不用最后关闭流了。帮你做了 try (InputStream inputStream = new FileInputStream(new File(folder, id + ".txt")); OutputStream outputStream = response.getOutputStream();) { //设置信息头 response.setContentType("application/x-download"); response.addHeader("Content-Disposition", "attachment;filename=test.txt");//filename 就是你下载到本地的名字 //意思是把输入流复制到输出流中 IOUtils.copy(inputStream, outputStream); outputStream.flush(); } } }
解决中文文件名————问题
String name = URLEncoder.encode(file.getFilename(), "utf-8")
依赖看引入的包。就不写了。
相关文章
- SpringMVC基础-12-异常处理
- SpringMVC之处理流程
- SpringMVC文件上传接口设计与实现
- ModelAndView + springMVC form:form
- springMVC,测试controller.
- SpringMVC+BUI实现文件上传(附详解,源码下载)
- 使用springMVC实现文件上传和下载之环境配置与上传
- mavn项目(springMVC) 引入静态资源(js、css)等
- 【SpringMVC笔记11】SpringMVC实现文件上传和下载
- 搭建Dynamic Web Project(动态web项目)的springmvc工程1
- Spring+SpringMVC+Mybatis(开发必备技能)03、图片上传
- springMVC学习笔记
- SpringMVC上传文件的MultipartFile源码
- [springMVC学习]1、springmvc设置spring配置文件
- SpringMVC+Mybatis搭建高性能安全站点