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实现文件上传下载的更多相关文章

  1. Spring Boot 教程 - 文件上传下载

    在日常的开发工作中,基本上每个项目都会有各种文件的上传和下载,大多数文件都是excel文件,操作excel的JavaAPI我用的是apache的POI进行操作的,POI我之后会专门讲到.此次我们不讲如 ...

  2. Spring Boot入门——文件上传与下载

    1.在pom.xml文件中添加依赖 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="ht ...

  3. spring boot:单文件上传/多文件上传/表单中多个文件域上传(spring boot 2.3.2)

    一,表单中有多个文件域时如何实现说明和文件的对应? 1,说明和文件对应 文件上传页面中,如果有多个文件域又有多个相对应的文件说明时, 文件和说明如何对应? 我们在表单中给对应的file变量和text变 ...

  4. spring mvc注解文件上传下载

    需要两个包: 包如何导入就不介绍了,前端代码如下(一定要加enctype="multipart/form-data"让服务器知道是文件上传): <form action=&q ...

  5. Spring Boot—04文件上传

    package com.smartmap.sample.ch1.controller.view; import java.io.File; import java.io.IOException; im ...

  6. spring mvc 实现文件上传下载

    /** * 文件上传 * @param pictureFile */ @RequestMapping("/reportupload") public ResponseInfo up ...

  7. spring boot Tomcat文件上传找不到零时文件夹

    springboot项目上传文件是找不到零时文件夹 1.本身启动jar包时内置Tomcat没有创建零时文件夹 2.在zuul网关级别没有创建零时文件夹 处理方案: -Djava.io.tmpdir=/ ...

  8. Spring Boot RestTemplate文件上传

    @ResponseBody @RequestMapping(value = "/upload.do", method = RequestMethod.POST) public St ...

  9. Spring boot设置文件上传大小限制

    原文:https://blog.csdn.net/lizhangyong1989/article/details/78586421 Spring boot1.0版本的application.prope ...

随机推荐

  1. 剑指Offer(书):剪绳子

    题目:给你一根长度为n的绳子,请把绳子剪成m段,每段绳子的长度记为k[0],k[1]....,k[m].请问k[0]xk[1]x...,k[m]可能的最大乘积是多少.例如:长度为8剪成2 3 3 得到 ...

  2. reversing.kr easykeygen 之wp

    补充: int(x,[base]): 就是将x(通常是一个字符串)按照base进制转换成整数. 比如: ’) ##转换成整数10 ) ##'按16进制转换,将得到整数16 ) ##得到255 int( ...

  3. LeetCode(27)Remove Element

    题目 Given an array and a value, remove all instances of that value in place and return the new length ...

  4. 使用JQuery.slideBox实现图片滚动效果

    1.下载JQuery.slideBox和jquery插件,并引用 <link href="css/jquery.slideBox.css" rel="stylesh ...

  5. 大数据学习——Hadoop第一天

    1.1 什么是HADOOP HADOOP是apache旗下的一套开源软件平台 HADOOP提供的功能:利用服务器集群,根据用户的自定义业务逻辑,对海量数据进行分布式处理 HADOOP的核心组件有 HD ...

  6. HDU 3973 线段树+字符串hash

    题目大意: 不断修改字符串中的字母,然后询问区间字符串是否处于已给定的字符串集合中 这里将原来的字符串集合保存到hash表中,当然用map,set都没有问题 修改查询都用线段树实现,自己的query函 ...

  7. 公路修建(Prim)

    洛谷传送门 这道水题告诉了我,堆优化的prim有时还不如朴素prim快... 居然记错时间复杂度了,我也真是菜. #include <cstdio> #include <queue& ...

  8. poj1975

    #include<stdio.h> #include<string.h> #define N 100 int map[N][N]; int main() { int t,n,m ...

  9. js中trim函数的简单实现

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <hea ...

  10. POJ 3620 Avoid The Lakes

    http://poj.org/problem?id=3620 DFS 从任意一个lake出发 重置联通的lake 并且记录 更新ans #include <iostream> #inclu ...