当前位置:网站首页>九、文件上传和下载
九、文件上传和下载
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";
}
边栏推荐
- [C language foundation] 13 preprocessor
- Huawei issued another global convening order of "genius youth", and some people once gave up their annual salary of 3.6 million to join
- 荐书丨《教育心理学》:送给明日教师的一本书~
- 数据仓库
- Matlab drawing
- How to transfer English documents to Chinese?
- Low cost, fast and efficient construction of digital collection app and H5 system, professional development of scallop technology is more assured!
- ROS2的launch有何不同?
- How does win11 set the theme color of the status bar? Win11 method of setting theme color of status bar
- Integrated architecture of performance and cost: modular architecture
猜你喜欢

荐书 |《学者的术与道》:写论文是门手艺

生活相关——十年的职业历程(转)

Acwing_ 12. Find a specific solution for the knapsack problem_ dp

I.MX6U-ALPHA开发板(主频和时钟配置实验)

低成本、快速、高效搭建数字藏品APP、H5系统,扇贝科技专业开发更放心!

Life related - ten years of career experience (turn)

UE4 多个角色控制权的切换

How does win11 22h2 skip networking and Microsoft account login?

The era of smart clothes has come. Zhinar invites you to discuss swords in Yangcheng. Guangya Exhibition is waiting for you on August 4

Apisex's exploration in the field of API and microservices
随机推荐
Weights & Biases (二)
VM virtual machine has no un bridged host network adapter, unable to restore the default configuration
Spark Structured Streaming HelloWorld
MySQL - multi table query - Cartesian product sum, correct multi table query, equivalent connection and unequal connection, inner connection and outer connection
Page pull-up refresh and pull-down loading
p-范数(2-范数 即 欧几里得范数)
生活相关——减少期待,更快乐
How to transfer English documents to Chinese?
[SVN] please execute the 'cleanup' command appears all the time. The solution is that there is no response after cleanup
How to write the abbreviation of the thesis?
生活相关——一个华科研究生导师的肺腑之言(主要适用于理工科)
吴恩达机器学习课后习题——逻辑回归
What are the consequences and problems of computer system restoration
Wu Enda's machine learning after class exercises - logical regression
APISIX 在 API 和微服务领域的探索
The auxiliary role of rational cognitive educational robot in teaching and entertainment
FFmpeg 视频编码
Web Test Method Encyclopedia
The difference between positive samples, negative samples, simple samples and difficult samples in deep learning (simple and easy to understand)
I.MX6U-ALPHA开发板(主频和时钟配置实验)