目录
  1. 1. 文件上传下载工具类
Springboot文件上传与下载

文件上传下载工具类

将上传下载进行封装以便在更多的地方使用到

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
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.net.URLEncoder;

public class FileUtils {

/**
*上传
*/
public static String upload(String path, MultipartFile file) throws IOException{
Path p = Paths.get(path, file.getOriginalFilename());
if (!Files.exists(p)){
Files.createDirectories(p);
}
Files.copy(file.getInputStream(), p, StandardCopyOption.REPLACE_EXISTING);
return p.toString();
}

/**
*下载
*/
public static ResponseEntity download(String path, String fileName) throws Exception {
FileSystemResource file = new FileSystemResource(path+fileName);
if (!file.exists()) throw new FileNotFoundException("Can't find file !");
return ResponseEntity.ok()
.headers(getHeaders(fileName))
.contentLength(file.contentLength())
.contentType(MediaType.parseMediaType("application/octet-stream"))
.body(new InputStreamResource(file.getInputStream()));
}

public static HttpHeaders getHeaders(String fileName) throws Exception {
//if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {
// fileName = URLEncoder.encode(fileName, "UTF-8");
//} else {
// fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
//}
HttpHeaders headers = new HttpHeaders();
headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
//headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", fileName));
String encodeFileName = URLEncoder.encode(fileName, "UTF-8");
headers.add("Content-Disposition", "attachment; filename=\"" + encodeFileName +"\"; filename*=utf-8''"+ encodeFileName);
headers.add("Pragma", "no-cache");
headers.add("Expires", "0");
return headers;
}
}
文章作者: 今晚早睡
文章链接: https://www.chensubao.com/article/17313.html
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 洛 苏り

评论