FileStore.java
2.5 KB
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
package com.server.utils;
import com.server.utils.key.QiniuKey;
import com.server.utils.key.UploadUrlKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
/**
* 本地文件存储
*/
@Component
public class FileStore {
private Logger log = LoggerFactory.getLogger(FileStore.class);
@Autowired
UploadUrlKey uploadUrlKey;
@Autowired
QiniuKey qiniuKey;
public String storeImage(String path, MultipartFile file) {
return store(path, file);
}
public String getRealPath(String path) {
String ret = uploadUrlKey.getRealPath() + "/" + path;
return ret.replaceAll("\\\\/+", "/");
}
public String store(String path, MultipartFile file) {
String originalName = file.getOriginalFilename();
int index = originalName.lastIndexOf(".");
String ext = index > -1 ? originalName.substring(index + 1) : ContentType.getExtension(file.getContentType());
String filename = UploadUtils.generateFilename(getRealPath(path), ext);
File dest = new File(filename);
dest = UploadUtils.getUniqueFile(dest);
dest = store(file, dest);
filename = dest.getAbsolutePath();
return filename.substring(filename.indexOf(uploadUrlKey.getBasePath()));
}
private File store(MultipartFile file, File dest) {
UploadUtils.checkDirAndCreate(dest.getParentFile());
try {
file.transferTo(dest);
} catch (IOException e) {
log.error("Transfer file error when upload file", e);
}
//如果是图片尝试纠图片方向
if (isImage(dest)) {
dest = compressImage(dest);
}
return dest;
}
private File compressImage(File dest) {
try {
Image image = new Image(dest);
if (image.getWidth() > 860 || image.getHeight() > 860) {
image.resize(860, 860, true);
}
image.saveAs(dest,uploadUrlKey,qiniuKey);
} catch (Exception e) {
e.printStackTrace();
}
return dest;
}
private boolean isImage(File file) {
try {
java.awt.Image image = ImageIO.read(file);
return image != null;
} catch (IOException ex) {
return false;
}
}
}