Remote http file upload and file2multipartfile in java
Keywords:
Java
JSON
There are times when you encounter various needs in your work, and you have to change your approach to solving them. Of course, what is important is in what scenarios to complete them.
For example, how the file type in Strut2 is converted to the multipartfile type, I looked for a few days and found a workaround documented below (although it didn't work in the end.):

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
It was not easy to write a complete remote upload method, and the local tests were working, but after submission a class could not be instantiated, debug found that it was a package incompatibility problem (embarrassing).
But you can't upgrade what others have used before, mainly because you don't have permission and have to go to the lower version to find a workaround similar to it, even if it's outdated.
//httpclient(4.5.3) Remote Transfer File Tool Class

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 = ""; // Request to return default support json strand
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 = ""; // Request to return default support json strand
15
16 HttpResponse httpResponse = null;
17
18 try {
19
20 HttpPost httpPost = new HttpPost(driverUrl);
21
22 //Set request and transport timeouts
23
24 RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(5000).build();
25
26 httpPost.setConfig(requestConfig);
27
28 // BTW 4.3 Version does not set timeout,Once the server does not respond,waiting time N long(>24 hour).
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("No results returned");
83
84 }
85
86 // Get the returned status code
87
88 int status = httpResponse.getStatusLine().getStatusCode();
89
90 logger.info("Post request URL="+driverUrl+",Requested parameters="+param.toString()+",Request Format"+contentType+",state="+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 request URL="+driverUrl+",Requested parameters="+param.toString()+",Request Format"+contentType+",error Code:"+status);
111
112 }
113
114 map.put("code", String.valueOf(status));
115
116 map.put("result", res);
117
118 logger.info("implement Post Result returned by method request = " + 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("call httpClient error", e);
149
150 throw new Exception("call httpClient error", 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 }
http remote file upload under 4.53 package

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 = ""; // Request to return default support json strand
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 // Get the returned status code
46
47 int status = httpResponse.getStatusLine().getStatusCode();
48
49 logger.info("Post request URL="+driverUrl+",Requested parameters="+param.toString()+",Request Format"+contentType+",state="+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 request URL="+driverUrl+",Requested parameters="+param.toString()+",Request Format"+contentType+",error Code:"+status);
70
71 }
72
73 map.put("code", String.valueOf(status));
74
75 map.put("result", res);
76
77 logger.info("implement Post Result returned by method request = " + res);
78
79 return map;
80
81 }