springboot实现文件上传和下载功能

时间:2022-09-13 14:30:58

spring boot 引入”约定大于配置“的概念,实现自动配置,节约了开发人员的开发成本,并且凭借其微服务架构的方式和较少的配置,一出来就占据大片开发人员的芳心。大部分的配置从开发人员可见变成了相对透明了,要想进一步熟悉还需要关注源码。

1.文件上传(前端页面):

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!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" rel="external nofollow" >下载</a>
</body>
</html>

 表单提交加上enctype="multipart/form-data"很重要,文件以二进制流的形式传输。

2.文件上传(后端java代码)支持多文件

Way1.使用MultipartHttpServletRequest来处理上传请求,然后将接收到的文件以流的形式写入到服务器文件中:

?
1
2
3
4
5
6
7
8
9
10
11
12
@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流:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// 文件上传
 @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配置文件

?
1
2
3
#上传文件大小设置
multipart.maxFileSize=500Mb
multipart.maxRequestSize=500Mb

4.文件下载将文件写到输出流里:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
@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.获取文件大小

?
1
2
3
4
5
6
7
8
9
10
11
12
13
// 文件大小转换
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()。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。