1 import org.apache.commons.fileupload.disk.DiskFileItem;
2 import org.springframework.web.multipart.MultipartFile;
3 import org.springframework.web.multipart.commons.CommonsMultipartFile;
4
5 import java.io.File;
6 import java.io.IOException;
7
8 public class MultipartToFile {
9 /**
10 * multfile转file
11 * @param multfile
12 * @return
13 * @throws IOException
14 */
15 public static File multipartToFile(MultipartFile multfile) throws IOException {
16 CommonsMultipartFile cf = (CommonsMultipartFile)multfile;
17 //这个myfile是MultipartFile的
18 DiskFileItem fi = (DiskFileItem) cf.getFileItem();
19 File file = fi.getStoreLocation();
20 //手动创建临时文件
21 if(file.length() < 2048){//如果文件小于2M,创建临时文件
22 File tmpFile = new File(System.getProperty("java.io.tmpdir") + System.getProperty("file.separator") +
23 file.getName());
24 multfile.transferTo(tmpFile);
25 return tmpFile;
26 }
27 return file;
28 }
29
30 /**
31 * 获取文件名称,除去后缀名
32 * @param filename
33 * @return
34 */
35 public static String getFileNameNoEx(String filename) {
36 if ((filename != null) && (filename.length() > 0)) {
37 int dot = filename.lastIndexOf('.');
38 if ((dot >-1) && (dot < (filename.length()))) {
39 return filename.substring(0, dot);
40 }
41 }
42 return filename;
43 }
44 }