工作中有时会遇到各种需求,你得变着法儿去解决,当然重要的是在什么场景中去完成。

比如Strut2中file类型如何转换成multipartfile类型,找了几天,发现一个变通的方法记录如下(虽然最后没有用上。。):

 1 private static MultipartFile getMulFileByPath(String picPath) {  
 2 
 3         FileItem fileItem = createFileItem(picPath);  
 4 
 5         MultipartFile mfile = new CommonsMultipartFile(fileItem);  
 6 
 7         return mfile;  
 8 
 9     }  
10 
11 
12 
13 private static FileItem createFileItem(String filePath)  
14 
15     {  
16 
17         FileItemFactory factory = new DiskFileItemFactory(16, null);  
18 
19         String textFieldName = "textField";  
20 
21         int num = filePath.lastIndexOf(".");  
22 
23         String extFile = filePath.substring(num);  
24 
25         FileItem item = factory.createItem(textFieldName, "text/plain", true,  
26 
27             "MyFileName" + extFile);  
28 
29         File newfile = new File(filePath);  
30 
31         int bytesRead = 0;  
32 
33         byte[] buffer = new byte[4096];  
34 
35         try  
36 
37         {  
38 
39             FileInputStream fis = new FileInputStream(newfile);  
40 
41             OutputStream os = item.getOutputStream();  
42 
43             while ((bytesRead = fis.read(buffer, 0, 8192))  
44 
45                 != -1)  
46 
47             {  
48 
49                 os.write(buffer, 0, bytesRead);  
50 
51             }  
52 
53             os.close();  
54 
55             fis.close();  
56 
57         }  
58 
59         catch (IOException e)  
60 
61         {  
62 
63             e.printStackTrace();  
64 
65         }  
66 
67         return item;  
68 
69     }  
file2multipartfile

相关文章:

  • 2022-12-23
  • 2021-12-31
  • 2022-12-23
  • 2022-12-23
  • 2021-05-05
  • 2021-10-13
  • 2021-11-18
猜你喜欢
  • 2021-10-16
  • 2022-12-23
  • 2022-01-22
  • 2022-12-23
  • 2022-02-23
  • 2021-09-09
  • 2021-08-22
相关资源
相似解决方案