文件上传和下载

文件上传和下载

页面文件

1
2
3
4
5
<form action="/file/upload" method="post" enctype="multipart/form-data">
<!--这里的名字要和后端接收的参数一样,并且要指定上传的是文件类型 enctype="multipart/form-data"-->
<input type="file" name="file">
<input type="submit" value="上传">
</form>

controller

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
@RestController
@RequestMapping("/file")
public class FileController {

@PostMapping("/upload")
public String upload(MultipartFile file) throws Exception {
// 获取上传文件的名字
String filename = file.getOriginalFilename();
// 定义文件输出流,第一个参数是本地文件路径,第二个是文件名
FileOutputStream outputStream = new FileOutputStream(new File("e:/upload/",filename));
// 将字节型数据写入输出流
outputStream.write(file.getBytes());
// 强制输出流将缓冲区中存在的所有数据写入目标文件
outputStream.flush();
// 关闭缓冲的输出流
outputStream.close();
return "上传成功";
}

@GetMapping("/download")
public void download(String filename, HttpServletResponse response) throws Exception{
// 获得文件输入流,第一个参数是本地文件路径,第二个是文件名
FileInputStream inputStream = new FileInputStream(new File("e:/upload/", filename));
// 设置响应头、以附件形式打开文件
response.setHeader("content-disposition", "attachment; filename=" + filename);
// 获取输出流
ServletOutputStream outputStream = response.getOutputStream();
int len = 0;
byte[] data = new byte[1024];
while ((len = inputStream.read(data)) != -1) {
//从输入流中读取一定数量的字节,并将其存储在缓冲区字节数组中,读到末尾返回-1
outputStream.write(data, 0, len);
}
// 关闭输入输出流
outputStream.close();
inputStream.close();

}

使用transferTo方法

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
@RestController
@RequestMapping("/file")
public class FileController {

@PostMapping("/upload")
public String upload(MultipartFile file) throws Exception {
// 获取源文件名
String originalFilename = file.getOriginalFilename();
// 获取路径,如果不存在则创建文件夹
Path path = Paths.get("e:/upload/");
if(!Files.exists(path)){
Files.createDirectory(path);
}
// 获取后缀并用UUID生成新的文件名,防止重名
String ext = originalFilename.substring(originalFilename.lastIndexOf(".")+1, originalFilename.length());
String newFileName = UUID.randomUUID().toString()+"."+ext;
// 执行文件上传,第一个参数是文件路径,第二个是文件名
file.transferTo(new File(String.valueOf(path),newFileName));
return "上传成功";
}

@GetMapping("/download")
public void download(String filename, HttpServletResponse response) throws Exception{
Path path = Paths.get("e:/upload/" + filename);
// 设置响应头、以附件形式打开文件
response.setHeader("content-disposition", "attachment; filename=" + filename);
// 创建新的输出流通道
WritableByteChannel writableByteChannel = Channels.newChannel(response.getOutputStream());
// 读取文件流通道
FileChannel fileChannel = new FileInputStream(path.toFile()).getChannel();
// 将文件通道中的数据复制到新通道
fileChannel.transferTo(0, fileChannel.size(), writableByteChannel);
// 通道关闭
fileChannel.close();
writableByteChannel.close();
}

}

文件上传和下载

作者

lvjie

发布于

2022-06-17

许可协议


:D 一言句子获取中...