FileUploadUtil.java
2.78 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
84
85
86
87
88
89
90
package com.bjivt.util;
import java.io.File;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
public class FileUploadUtil {
/**
* @Title: FileUploadUtil.java
* @Package com.enla.util
* @Description: 上传公共
* @author JASON
* @date 2015-7-17
* @param filePath
* 文件上传路径 (/uploadimgfile/xxx)
* @param multipartFile
*/
public static String fileUpload(MultipartFile multipartFile, String filePath, HttpServletRequest request)
throws Exception {
/** 得到图片保存目录的真实路径 **/
String logoRealPathDir = request.getSession().getServletContext().getRealPath(filePath);
/** 根据真实路径创建目录 **/
File file = new File(logoRealPathDir);
if (!file.exists())
file.mkdirs();
/** 获取文件的后缀 **/
String suffix = multipartFile.getOriginalFilename();
if (StringUtils.isNotBlank(suffix)) {
suffix = suffix.substring(multipartFile.getOriginalFilename().lastIndexOf("."));
/** 生成文件名称 **/
String code = CodeCreator.generateCharArr(12);
String fileName = code + suffix;
/** 拼成完整的文件保存路径加文件 **/
String fileSavePath = logoRealPathDir + File.separator + fileName;// 上传文件完整路径
String fileDbPath = filePath + "/" + fileName; // 保存到数据库的相对路径
File targetFile = new File(fileSavePath);
try {
multipartFile.transferTo(targetFile);
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return fileSavePath+";"+fileDbPath;
}
return "";
}
/**
public static String fileUpload(MultipartFile multipartFile, String filePath, HttpServletRequest request)
throws Exception {
String logoRealPathDir = request.getSession().getServletContext().getRealPath(filePath);
File file = new File(logoRealPathDir);
if (!file.exists())
file.mkdirs();
String suffix = multipartFile.getOriginalFilename();
if (StringUtils.isNotBlank(suffix)) {
suffix = suffix.substring(multipartFile.getOriginalFilename().lastIndexOf("."));
String code = CodeCreator.generateCharArr(12);
String fileName = code + suffix;
String fileSavePath = logoRealPathDir + File.separator + fileName;// 上传文件完整路径
String fileDbPath = filePath + "/" + fileName; // 保存到数据库的相对路径
File targetFile = new File(fileSavePath);
try {
multipartFile.transferTo(targetFile);
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return fileDbPath;
}
return "";
}
**/
}