当前位置:网站首页>九、文件上传和下载
九、文件上传和下载
2022-07-26 04:27:00 【时间邮递员】
1、文件下载
使用ResponseEntity实现下载文件的功能
package com.yzh.controller;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
@Controller
public class FileController {
@RequestMapping("/testDownload")
public ResponseEntity<byte[]> testResponseEntity(HttpSession session) throws IOException {
//获取ServletContext对象
ServletContext servletContext = session.getServletContext();
//获取服务器中文件的真实路径
String realPath = servletContext.getRealPath("/static/img/img1.jpg");
System.out.println(realPath);
//创建输入流
InputStream inputStream = new FileInputStream(realPath);
//创建字节数组
byte[] bytes = new byte[inputStream.available()];
//将流读到字节数组中
inputStream.read(bytes);
//创建HttpHeaders对象设置响应头信息
MultiValueMap<String, String> headers = new HttpHeaders();
//设置要下载方式以及下载文件的名字
headers.add("Content-Disposition", "attachment;filename=img1.jpg");
//设置响应状态码
HttpStatus statusCode = HttpStatus.OK;
//创建ResponseEntity对象
ResponseEntity<byte[]> responseEntity = new ResponseEntity<byte[]>(bytes, headers, statusCode);
//关闭输入流
inputStream.close();
return responseEntity;
}
}
2、文件上传
文件上传要求form表单的请求方式必须为post,并且添加属性enctype=“multipart/form-data”
<form th:action="@{/testUp}" method="post" enctype="multipart/form-data">
好看图片:<input type="file" name="photo">
<input type="submit" value="文件上传">
</form>
SpringMVC中将上传的文件封装到MultipartFile对象中,通过此对象可以获取文件相关信息
上传步骤:
a>添加依赖
<!-- commons-fileupload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
b>在SpringMVC的配置文件中添加配置
<!--必须通过文件解析器的解析才能将文件转换为MultipartFile对象-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>
c>控制器方法
@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";
}
边栏推荐
- Graph theory: topological sorting
- MySQL log classification: error log, binary log, query log, slow query log
- Function knowledge points
- Support proxy direct connection to Oracle database, jumpserver fortress v2.24.0 release
- 【学习笔记】AGC041
- 软模拟光栅化渲染器
- What are the duplicate check rules for English papers?
- 吴恩达机器学习课后习题——逻辑回归
- 建设面向青少年的创客教育实验室
- Dynamic planning for stair climbing
猜你喜欢

How to transfer English documents to Chinese?

软模拟光栅化渲染器

综合评价与决策方法

Li Kou daily question - day 42 -661. Picture smoother

第三篇如何使用SourceTree提交代码

Build a maker Education Laboratory for teenagers

力扣每日一题-第42天-661. 图片平滑器

RTSP/Onvif协议视频平台EasyNVR服务一键升级功能的使用教程

荐书丨《教育心理学》:送给明日教师的一本书~

How mantium uses deepspeed to implement low latency gpt-j reasoning on Amazon sagemaker
随机推荐
Day26 job
RTSP/Onvif协议视频平台EasyNVR服务一键升级功能的使用教程
How to download the supplementary literature?
Swiftui one day crash
MapReduce中分区数与ReduceTask个数关系比较
Use of rule engine drools
APISIX 在 API 和微服务领域的探索
Page pull-up refresh and pull-down loading
Acwing刷题
Build a maker Education Laboratory for teenagers
Firewall command simple operation
How to transfer English documents to Chinese?
How to choose the key words of the thesis?
MySQL only checks the reasons for the slow execution of one line statements
Function knowledge points
Graph translation model
Day24 job
How does win11 change the power mode? Win11 method of changing power mode
FFmpeg 视频编码
SwiftUI一日速成