1. 程式人生 > >java中遠程http文件上傳及file2multipartfile

java中遠程http文件上傳及file2multipartfile

valueof 返回 file mob pic multipart .post ntp pst

工作中有時會遇到各種需求,你得變著法兒去解決,當然重要的是在什麽場景中去完成。

比如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

好不容易寫好了一個完整的遠程上傳方法,並且本地測試已經通過能用,提交後發現有個類實例化不了,debug發現是包不兼容問題(尷尬),

但是以前別人用過的東西,你又不能升級,主要是沒權限,不得不去低級的版本中找變通的類似方法,即便方法已經過時了。。

//httpclient(4.5.3)遠程傳輸文件工具類

技術分享圖片
  1 public static Map<String, String> executeDriverServer(String driverUrl, Map<String, Object> param,String multipart, String contentType,int timeout,String picPath) throws Exception {
  2 
  3         String res = ""; // 請求返回默認的支持json串
  4 
  5         Map<String, String> map = new HashMap<String, String>();
  6                 ContentType ctype = ContentType.create("content-disposition","UTF-8");
  7 
  8         Map<String, String> map = new HashMap<String, String>();
  9 
 10         HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
 11 
 12         CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
 13 
 14         String res = ""; // 請求返回默認的支持json串
 15 
 16         HttpResponse httpResponse = null;
 17 
 18         try {
 19 
 20             HttpPost httpPost = new HttpPost(driverUrl);
 21 
 22             //設置請求和傳輸超時時間
 23 
 24             RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(5000).build();
 25 
 26             httpPost.setConfig(requestConfig);
 27 
 28             // BTW 4.3版本不設置超時的話,一旦服務器沒有響應,等待時間N久(>24小時)。 
 29 
 30             if(httpPost!=null){
 31 
 32                 if("formdata".equals(multipart)){
 33 
 34                     MultipartEntityBuilder mentity = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532);
 35 
 36                     Set<String> keyset = param.keySet();
 37 
 38                     for (String key : keyset) {
 39 
 40                         Object paramObj = Validate.notNull(param.get(key));
 41 
 42                         if(paramObj instanceof MultipartFile) {
 43 
 44                             mentity.addBinaryBody(key, ((MultipartFile) paramObj).getInputStream(),ctype,((MultipartFile) paramObj).getOriginalFilename());
 45 
 46                         }else if(paramObj instanceof File){
 47 
 48                             mentity.addBinaryBody(key, (File)paramObj);//(key, new FileInputStream((File)paramObj),ctype,((File)paramObj).getName());
 49 
 50                         }else{
 51 
 52                             mentity.addPart(key,new StringBody(paramObj.toString(),ctype));
 53 
 54                             //mentity.addTextBody(key,paramObj.toString());
 55 
 56                         }
 57 
 58                         logger.info("key::::"+key);
 59 
 60                         logger.info("paramObj::::"+paramObj.toString());
 61 
 62                     }
 63 
 64                     HttpEntity entity = mentity.build();
 65 
 66                     HttpUriRequest post =  RequestBuilder.post().setUri(driverUrl).setEntity(entity).build();
 67 
 68                     httpResponse = closeableHttpClient.execute(post);
 69 
 70                 }else {
 71 
 72                     HttpEntity entity = convertParam(param, contentType);
 73 
 74                     httpPost.setEntity(entity);
 75 
 76                     httpResponse = closeableHttpClient.execute(httpPost);
 77 
 78                 }
 79 
 80                 if(httpResponse == null) {
 81 
 82                     throw new Exception("無返回結果");
 83 
 84                 }
 85 
 86                 // 獲取返回的狀態碼
 87 
 88                 int status = httpResponse.getStatusLine().getStatusCode();
 89 
 90                 logger.info("Post請求URL="+driverUrl+",請求的參數="+param.toString()+",請求的格式"+contentType+",狀態="+status);
 91 
 92                 if(status == HttpStatus.SC_OK){
 93 
 94                     HttpEntity entity2 = httpResponse.getEntity();
 95 
 96                     InputStream ins = entity2.getContent();
 97 
 98                     res = toString(ins);
 99 
100                     ins.close();
101 
102                 }else{
103 
104                     InputStream fis = httpResponse.getEntity().getContent();
105 
106                     Scanner sc = new Scanner(fis);
107 
108                     logger.info("Scanner:::::"+sc.next());
109 
110                     logger.error("Post請求URL="+driverUrl+",請求的參數="+param.toString()+",請求的格式"+contentType+",錯誤Code:"+status);
111 
112                 }
113 
114                 map.put("code", String.valueOf(status));
115 
116                 map.put("result", res);
117 
118                 logger.info("執行Post方法請求返回的結果 = " + res);
119 
120             }
121 
122         } catch (ClientProtocolException e) {
123 
124             map.put("code", HttpClientUtil.CLIENT_PROTOCOL_EXCEPTION_STATUS);
125 
126             map.put("result", e.getMessage());
127 
128         } catch (UnsupportedEncodingException e) {
129 
130             map.put("code", HttpClientUtil.UNSUPPORTED_ENCODING_EXCEPTION_STATUS);
131 
132             map.put("result", e.getMessage());
133 
134         } catch (IOException e) {
135 
136             map.put("code", HttpClientUtil.IO_EXCEPTION_STATUS);
137 
138             map.put("result", e.getMessage());
139 
140         } finally {
141 
142             try {
143 
144                 closeableHttpClient.close();
145 
146             } catch (IOException e) {
147 
148                 logger.error("調用httpClient出錯", e);
149 
150                 throw new Exception("調用httpClient出錯", e);
151 
152             }
153 
154         }
155 
156 
157 
158 private static String toString(InputStream in) throws IOException{
159 
160         ByteArrayOutputStream os = new ByteArrayOutputStream();
161 
162         byte[] b = new byte[1024];
163 
164         int len;
165 
166         while((len = in.read(b)) != -1) {
167 
168             os.write(b, 0, len);
169 
170         }
171 
172         return os.toString("UTF-8");
173 
174     }
175 }
4.53包下http遠程文件上傳

//httpclient(4.2.2)老版本遠程傳輸文件工具類

技術分享圖片
 1 public static Map<String, String> executeDriverServer(String driverUrl, Map<String, Object> param,String multipart, String contentType,int timeout,String picPath) throws Exception {
 2 
 3         String res = ""; // 請求返回默認的支持json串
 4 
 5         Map<String, String> map = new HashMap<String, String>();
 6 
 7         ContentType ctype = ContentType.create("content-disposition","UTF-8");
 8 
 9         HttpPost httpPost = new HttpPost(driverUrl);
10 
11         MultipartEntity reqEntity = new MultipartEntity();
12 
13         Set<String> keyset = param.keySet();
14 
15         File tempFile = new File(picPath);
16 
17         for (String key : keyset) {
18 
19             Object paramObj = Validate.notNull(param.get(key));
20 
21             if(paramObj instanceof File) {
22 
23                 FileBody fileBody = new FileBody(tempFile);
24 
25                 reqEntity.addPart(key, fileBody);
26 
27             }else{
28 
29                 reqEntity.addPart(key,new StringBody(paramObj.toString()));
30 
31             }
32 
33             logger.info("key::::"+key);
34 
35             logger.info("paramObj::::"+paramObj.toString());
36 
37         }
38 
39         httpPost.setEntity(reqEntity);
40 
41         HttpClient httpClient = new DefaultHttpClient();
42 
43         HttpResponse httpResponse = httpClient.execute(httpPost);
44 
45         // 獲取返回的狀態碼
46 
47         int status = httpResponse.getStatusLine().getStatusCode();
48 
49         logger.info("Post請求URL="+driverUrl+",請求的參數="+param.toString()+",請求的格式"+contentType+",狀態="+status);
50 
51         if(status == HttpStatus.SC_OK){
52 
53             HttpEntity entity2 = httpResponse.getEntity();
54 
55             InputStream ins = entity2.getContent();
56 
57             res = toString(ins);
58 
59             ins.close();
60 
61         }else{
62 
63             InputStream fis = httpResponse.getEntity().getContent();
64 
65             Scanner sc = new Scanner(fis);
66 
67             logger.info("Scanner:::::"+sc.next());
68 
69             logger.error("Post請求URL="+driverUrl+",請求的參數="+param.toString()+",請求的格式"+contentType+",錯誤Code:"+status);
70 
71         }
72 
73         map.put("code", String.valueOf(status));
74 
75         map.put("result", res);
76 
77         logger.info("執行Post方法請求返回的結果 = " + res);
78 
79         return map;
80 
81     }
4.2.2版本http遠程傳輸文件工具類

希望對大家有點幫助!平常心。

java中遠程http文件上傳及file2multipartfile