SpringBoot-(十一)SpringBoot实现文件上传

本文最后更新于:February 16, 2022 pm

SpringBoot框架中有两个非常重要的策略:开箱即用和约定优于配置。其设计目的是用来简化新Spring应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。

目录

准备

用到Hutool的工具:

1
2
3
4
5
6
7
8
9
10
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.7.20</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>

数据库:

1
2
3
4
5
6
7
8
9
10
CREATE TABLE `file` (
`id` int NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL COMMENT '文件名称',
`type` varchar(30) DEFAULT NULL,
`size` bigint DEFAULT NULL, # 存储kb
`url` varchar(255) DEFAULT NULL,
`is_delete` tinyint(1) DEFAULT '0', # 是否删除,默认0为没删除
`enable` tinyint(1) DEFAULT '0', # 链接是否可以访问,默认0为可以访问
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci

设置文件上传的位置

在主配置文件中:

1
2
3
files: # 上传文件的位置
upload:
path: F:/idea2022Test/home/files/

上传

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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package com.tothefor.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.tothefor.dao.FilesMapper;
import com.tothefor.pojo.entity.Files;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;

@RestController
@RequestMapping("/file")
public class FileController {

@Value("${files.upload.path}")
private String fileUploadPath;

@Resource
private FilesMapper fileMapper;


/**
* 文件上传
* @param file
* @return
* @throws IOException
*/
@PostMapping("/upload")
public String upload(@RequestParam MultipartFile file) throws IOException {
String odername = file.getOriginalFilename(); //原始名称
String type = FileUtil.extName(odername); //通过hutool工具类获取类型
long size =file.getSize();

File uploadParentFile = new File(fileUploadPath);

if(!uploadParentFile.exists()){ //配置的文件目录是否存在,不存在则创建
uploadParentFile.mkdirs();
}
//定义文件唯一标识码
String uuid = IdUtil.fastSimpleUUID();
String fileuuid = uuid+StrUtil.DOT+type;//重命名
File uploadFile = new File(fileUploadPath+fileuuid);
//将上传并处理后的文件进行存储到指定位置
file.transferTo(uploadFile);

String url = "http://localhost:8081/file/"+fileuuid;

Files myfile = new Files();
myfile.setName(odername);
myfile.setType(type);
myfile.setSize(size/1024); //从b转化为kb
myfile.setUrl(url);
fileMapper.insert(myfile); //文件mapper,insert是插入数据

return url;
}


}

下载

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
44
45
46
47
48
49
50
51
package com.tothefor.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.tothefor.dao.FilesMapper;
import com.tothefor.pojo.entity.Files;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;

@RestController
@RequestMapping("/file")
public class FileController {

@Value("${files.upload.path}")
private String fileUploadPath;

@Resource
private FilesMapper fileMapper;

/**
* http://localhost:8081/file/{fileuuid}
* @param fileuuid
* @param response
* @throws IOException
*/
@GetMapping("/{fileuuid}")
public void download(@PathVariable String fileuuid, HttpServletResponse response) throws IOException {
//根据文件的唯一标识码获取文件
File uploadFile = new File(fileUploadPath+fileuuid); //重命名
//设置输出流的格式
ServletOutputStream os = response.getOutputStream();
response.addHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileuuid,"UTF-8"));
response.setContentType("application/octet-stream");

// 读取文件字节流
os.write(FileUtil.readBytes(uploadFile));
os.flush();
os.close();
}

}

完整上传和下载

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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package com.tothefor.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.tothefor.dao.FilesMapper;
import com.tothefor.pojo.entity.Files;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;

@RestController
@RequestMapping("/file")
public class FileController {

@Value("${files.upload.path}")
private String fileUploadPath;

@Resource
private FilesMapper fileMapper;


/**
* 文件上传
* @param file
* @return
* @throws IOException
*/
@PostMapping("/upload")
public String upload(@RequestParam MultipartFile file) throws IOException {
String odername = file.getOriginalFilename(); //原始名称
String type = FileUtil.extName(odername); //通过hutool工具类获取类型
long size =file.getSize();

File uploadParentFile = new File(fileUploadPath);

if(!uploadParentFile.exists()){ //配置的文件目录是否存在,不存在则创建
uploadParentFile.mkdirs();
}
//定义文件唯一标识码
String uuid = IdUtil.fastSimpleUUID();
String fileuuid = uuid+StrUtil.DOT+type;//重命名
File uploadFile = new File(fileUploadPath+fileuuid);
//将上传并处理后的文件进行存储到指定位置
file.transferTo(uploadFile);

String url = "http://localhost:8081/file/"+fileuuid; //此处的file是设置url,而不是文件存储位置的files,即:应该写访问此controller的主RequestMapping路径

Files myfile = new Files();
myfile.setName(odername);
myfile.setType(type);
myfile.setSize(size/1024); //从b转化为kb
myfile.setUrl(url);
fileMapper.insert(myfile);

return url;
}

/**
* http://localhost:8081/file/{fileuuid}
* @param fileuuid
* @param response
* @throws IOException
*/
@GetMapping("/{fileuuid}")
public void download(@PathVariable String fileuuid, HttpServletResponse response) throws IOException {
//根据文件的唯一标识码获取文件
File uploadFile = new File(fileUploadPath+fileuuid); //重命名
//设置输出流的格式
ServletOutputStream os = response.getOutputStream();
response.addHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileuuid,"UTF-8"));
response.setContentType("application/octet-stream");

// 读取文件字节流
os.write(FileUtil.readBytes(uploadFile));
os.flush();
os.close();
}

}

文件去重

通过MD5识别。