在SSM框架中,multfile轉file

木子小僧發表於2017-12-04
 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 }

 

相關文章