spring boot实现文件上传下载
spring boot 引入”约定大于配置“的概念,实现自动配置,节约了开发人员的开发成本,并且凭借其微服务架构的方式和较少的配置,一出来就占据大片开发人员的芳心。大部分的配置从开发人员可见变成了相对透明了,要想进一步熟悉还需要关注源码。
1.文件上传(前端页面):
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="/testUpload" method="POST" enctype="multipart/form-data">
<input type="file" name="file"/>
<input type="submit" />
</form>
<a href="/testDownload">下载</a>
</body>
</html>
表单提交加上enctype="multipart/form-data"很重要,文件以二进制流的形式传输。
2.文件上传(后端java代码)支持多文件
Way1.使用MultipartHttpServletRequest来处理上传请求,然后将接收到的文件以流的形式写入到服务器文件中:
@RequestMapping(value="/testUpload",method=RequestMethod.POST)
public void testUploadFile(HttpServletRequest req,MultipartHttpServletRequest multiReq) throws IOException{
FileOutputStream fos=new FileOutputStream(new File("F://test//src//file//upload.jpg"));
FileInputStream fs=(FileInputStream) multiReq.getFile("file").getInputStream();
byte[] buffer=new byte[1024];
int len=0;
while((len=fs.read(buffer))!=-1){
fos.write(buffer, 0, len);
}
fos.close();
fs.close();
}
Way2.也可以这样来取得上传的file流:
// 文件上传
@RequestMapping("/fileUpload")
public Map fileUpload(@RequestParam("file") MultipartFile file, HttpServletRequest req) {
Map result = new HashMap();
SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");// 设置日期格式
String dateDir = df.format(new Date());// new Date()为获取当前系统时间
String serviceName = UuidUtil.get32UUID()
+ file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
File tempFile = new File(fileDir + dateDir + File.separator + serviceName);
if (!tempFile.getParentFile().exists()) {
tempFile.getParentFile().mkdirs();
}
if (!file.isEmpty()) {
try {
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(tempFile));
// "d:/"+file.getOriginalFilename() 指定目录
out.write(file.getBytes());
out.flush();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
result.put("msg", "上传失败," + e.getMessage());
result.put("state", false);
return result;
} catch (IOException e) {
e.printStackTrace();
result.put("msg", "上传失败," + e.getMessage());
result.put("state", false);
return result;
}
result.put("msg", "上传成功");
String fileId = Get8uuid.generateShortUuid();
String fileName = file.getOriginalFilename();
String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
String fileUrl = webDir + dateDir + '/' + serviceName;
uploadMapper.saveFileInfo(fileId, serviceName, fileType, fileUrl);
result.put("state", true);
return result;
} else {
result.put("msg", "上传失败,因为文件是空的");
result.put("state", false);
return result;
}
3.application.properties配置文件
#上传文件大小设置
multipart.maxFileSize=500Mb
multipart.maxRequestSize=500Mb
4.文件下载将文件写到输出流里:
@RequestMapping(value="/testDownload",method=RequestMethod.GET)
public void testDownload(HttpServletResponse res) throws IOException{
File file = new File("C:/test.txt");
resp.setHeader("content-type", "application/octet-stream");
resp.setContentType("application/octet-stream");
resp.setHeader("Content-Disposition", "attachment;filename=" + fileName);
byte[] buff = new byte[1024];
BufferedInputStream bis = null;
OutputStream os = null;
try {
os = resp.getOutputStream();
bis = new BufferedInputStream(new FileInputStream(file));
int i = bis.read(buff);
while (i != -1) {
os.write(buff, 0, buff.length);
os.flush();
i = bis.read(buff);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
5.获取文件大小
// 文件大小转换
DecimalFormat df1 = new DecimalFormat("0.00");
String fileSizeString = "";
long fileSize = file.getSize();
if (fileSize < 1024) {
fileSizeString = df1.format((double) fileSize) + "B";
} else if (fileSize < 1048576) {
fileSizeString = df1.format((double) fileSize / 1024) + "K";
} else if (fileSize < 1073741824) {
fileSizeString = df1.format((double) fileSize / 1048576) + "M";
} else {
fileSizeString = df1.format((double) fileSize / 1073741824) + "G";
}
如果是File类则fileSize=file.length()。
spring boot实现文件上传下载的更多相关文章
- Spring Boot 教程 - 文件上传下载
在日常的开发工作中,基本上每个项目都会有各种文件的上传和下载,大多数文件都是excel文件,操作excel的JavaAPI我用的是apache的POI进行操作的,POI我之后会专门讲到.此次我们不讲如 ...
- Spring Boot入门——文件上传与下载
1.在pom.xml文件中添加依赖 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="ht ...
- spring boot:单文件上传/多文件上传/表单中多个文件域上传(spring boot 2.3.2)
一,表单中有多个文件域时如何实现说明和文件的对应? 1,说明和文件对应 文件上传页面中,如果有多个文件域又有多个相对应的文件说明时, 文件和说明如何对应? 我们在表单中给对应的file变量和text变 ...
- spring mvc注解文件上传下载
需要两个包: 包如何导入就不介绍了,前端代码如下(一定要加enctype="multipart/form-data"让服务器知道是文件上传): <form action=&q ...
- Spring Boot—04文件上传
package com.smartmap.sample.ch1.controller.view; import java.io.File; import java.io.IOException; im ...
- spring mvc 实现文件上传下载
/** * 文件上传 * @param pictureFile */ @RequestMapping("/reportupload") public ResponseInfo up ...
- spring boot Tomcat文件上传找不到零时文件夹
springboot项目上传文件是找不到零时文件夹 1.本身启动jar包时内置Tomcat没有创建零时文件夹 2.在zuul网关级别没有创建零时文件夹 处理方案: -Djava.io.tmpdir=/ ...
- Spring Boot RestTemplate文件上传
@ResponseBody @RequestMapping(value = "/upload.do", method = RequestMethod.POST) public St ...
- Spring boot设置文件上传大小限制
原文:https://blog.csdn.net/lizhangyong1989/article/details/78586421 Spring boot1.0版本的application.prope ...
随机推荐
- LeetCode(18)4Sum
题目 Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = ...
- 3.3.4 使用 awk 重新编排字段
awk 本身所提供的功能完备,已经是一个很好用的程序语言了.以后会好好地介绍该语言的精髓.虽然 awk 能做的事很多,但它主要的设计是要在 Shell脚本中发挥所长:做一些简单的文本处理,例如取出字段 ...
- 大数据学习——下载集群根目录下的文件到E盘
代码如下: package cn.itcast.hdfs; import java.io.IOException; import org.apache.hadoop.conf.Configuratio ...
- python出现'module' object is not callable错误
- PHP建立和删除目录
<?php/*linux中的文件权限filedir 用户 组 其它 rwx rwx rwx 读写执行 6 4 6 读写 读 读写 7 7 7 rw_ r__ rw_ r__ _w_ ___ r ...
- msp430入门编程17
msp430中C语言的寄存器操作 msp430入门学习 msp430入门编程
- MySQL性能优化的21个最佳实践 和 mysql使用索引【转载】
今天,数据库的操作越来越成为整个应用的性能瓶颈了,这点对于Web应用尤其明显.关于数据库的性能,这并不只是DBA才需要担心的事,而这更是我 们程序员需要去关注的事情.当我们去设计数据库表结构,对操作数 ...
- PostgreSQL 9.3.1 中文手册(解决关键词报错的问题)
http://www.postgres.cn/docs/9.3/sql-keywords-appendix.html
- Hive安装中遇到过的坑
实现说明每一个用户的环境都有细微的不一致,所以这里只是个人经过这些坑的处理,但是不意味着所有处理都是这样的操作,仅作为参考. 第一个坑 数据库安装,数据库最好装在Linux上,一直出了很多错,这里有一 ...
- MySQL查询在一个表而不在另一个表中的数据
1.使用not in,容易理解,效率低 select distinct A.ID from A where A.ID not in (select ID from B) 2.使用left join.. ...