springMVC 文件上传和下载

文章目录

1、文件下载

使用ResponseEntity实现下载文件的功能

java 复制代码
@RequestMapping("/testDown")
public ResponseEntity<byte[]> testResponseEntity(HttpSession session) throws IOException {
    //获取ServletContext对象
    ServletContext servletContext = session.getServletContext();
    //获取服务器中文件的真实路径
    String realPath = servletContext.getRealPath("/static/img/1.jpg");
    //创建输入流
    InputStream is = new FileInputStream(realPath);
    //创建字节数组
    byte[] bytes = new byte[is.available()];
    //将流读到字节数组中
    is.read(bytes);
    //创建HttpHeaders对象设置响应头信息
    MultiValueMap<String, String> headers = new HttpHeaders();
    //设置要下载方式以及下载文件的名字
    headers.add("Content-Disposition", "attachment;filename=1.jpg");
    //设置响应状态码
    HttpStatus statusCode = HttpStatus.OK;
    //创建ResponseEntity对象
    ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, headers, statusCode);
    //关闭输入流
    is.close();
    return responseEntity;
}

2、文件上传

文件上传要求form表单的请求方式必须为post,并且添加属性enctype="multipart/form-data"

SpringMVC中将上传的文件封装到MultipartFile对象中,通过此对象可以获取文件相关信息

上传步骤:

(1)添加依赖:

xml 复制代码
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.1</version>
</dependency>

(2)在SpringMVC的配置文件中添加配置:

xml 复制代码
<!--必须通过文件解析器的解析才能将文件转换为MultipartFile对象-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>

(3)控制器方法:

java 复制代码
@RequestMapping("/testUp")
public String testUp(MultipartFile photo, HttpSession session) throws IOException {
    //获取上传的文件的文件名
    String fileName = photo.getOriginalFilename();
    //处理文件重名问题
    String hzName = fileName.substring(fileName.lastIndexOf("."));
    fileName = UUID.randomUUID().toString() + hzName;
    //获取服务器中photo目录的路径
    ServletContext servletContext = session.getServletContext();
    String photoPath = servletContext.getRealPath("photo");
    File file = new File(photoPath);
    if(!file.exists()){
        file.mkdir();
    }
    String finalPath = photoPath + File.separator + fileName;
    //实现上传功能
    photo.transferTo(new File(finalPath));
    return "success";
}

文件在的位置:

相关推荐
陈如水35 分钟前
尚硅谷 Spring AI学习
人工智能·python·spring
长不大的杨瑞杰1 小时前
Spring Boot 4 + Java 25 虚拟线程实战:配置、压测、限流与线上排障
java·spring boot·后端·spring·软件工程
Forget the Dream2 小时前
Spring AI 2.0 系列(四):Starter 与 OpenAI-compatible:一个不绑死厂商的模型环境
java·人工智能·spring·springai
_waylau3 小时前
Spring AI开发从入门到实践-Spring AI的应用场景与未来展望
java·人工智能·后端·spring·llm·spring ai
会编程的吕洞宾3 小时前
Spring AI 多轮对话总失忆?ChatMemory 持久化实战
java·人工智能·经验分享·后端·spring
Yetian_20003 小时前
Spring MVC常用注解整理
java·spring·mvc
FYKJ_20106 小时前
springboot高校实验室综合管理系统86531-计算机毕业设计、课程设计
java·vue.js·spring boot·后端·python·spring·课程设计
洋不写bug13 小时前
Spring IoC & DI 超详细解析
spring·di·javaee·spring ioc·类注解·方法注解·扫描路径
master33616 小时前
基于 Spring AI + Spring Cloud 构建 Web 版 AI Chat:多模型接入、流式对话与全链路验证
人工智能·spring·spring cloud
骑着蜗牛撵大象32720 小时前
AgentScope 搭大脑、Spring AI 当手脚:企业智能体推理与执行分层落地
java·人工智能·spring·智能体·工具调用·agentscope·模型编排