OssUtils.java
15.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
package com.lhcredit.common.utils;
import cn.hutool.core.io.resource.InputStreamResource;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.InputStreamBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.CharsetUtils;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.Key;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@RestController
@RequestMapping("/web/upLoadFile")
public class OssUtils {
private static String ossUrl = "http://101.200.76.6:8085";
// private static String ossUrl="http://localhost:8095";
/**
*
* @param file 上传文件
* @param useOriginalFilename 是否使用原文件名
* @param noRestrict 是否无限制附件类型
* @return
*/
@PostMapping
public AnnexInfo uploadFile(MultipartFile file, String useOriginalFilename,String noRestrict) {
if (null==file)return AnnexInfo.builder().code(5000).msg("文件为空").build();
useOriginalFilename=StringUtils.isEmpty(useOriginalFilename)?"false":"true";
noRestrict=StringUtils.isEmpty(noRestrict)?"false":"true";
String post = POST(ossUrl + "/oss/standardAnnax", null, file, file.getOriginalFilename(), noRestrict, useOriginalFilename);
AnnexInfo annexInfo = JSONObject.parseObject(post, AnnexInfo.class);
return annexInfo;
}
@RequestMapping("downloadUrl")
public void downloadUrl(String url, HttpServletResponse response) {
downloadUrlForResponse(url,response);
}
/**
* 本地测试 获取生成token
*/
public static void main(String[] args) {
System.out.println(getToken());
}
/**
* 标准附件 格式受限"jpg","png","pdf","doc","txt","docx","xlsx","xls","ppt"
*/
public static AnnexInfo standardAnnax(MultipartFile file) {
try {
String post = POST(ossUrl + "/oss/standardAnnax", null, file, file.getOriginalFilename(),"false","false");
return JSONObject.parseObject(post, AnnexInfo.class);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static AnnexInfo standardAnnax2(MultipartFile file) {
try {
// String post = POST(ossUrl + "/oss/standardAnnax", null, file, file.getOriginalFilename(),"false","false");
// return JSONObject.parseObject(post, AnnexInfo.class);
JSONObject jsonObject = doPostFormData(ossUrl + "/oss/import", file.getOriginalFilename(), file, new HashMap<>());
System.out.println(jsonObject.toJSONString());
return new AnnexInfo();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 标准附件 格式受限"jpg","png","pdf","doc","txt","docx","xlsx","xls","ppt"
*/
public static AnnexInfo standardAnnax(File file) {
try {
String post = POST(ossUrl + "/oss/standardAnnex", new FileInputStream(file), null, file.getName(),"false","false");
return JSONObject.parseObject(post, AnnexInfo.class);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 根据 文件原名称上传 文件
* @param multipartFile
* @param file
* @return
*/
public static AnnexInfo useOriginalFilename(MultipartFile multipartFile,File file){
try {
String post = POST(ossUrl + "/oss/useOriginalFilename", null!=file?new FileInputStream(file):null, null!=multipartFile?multipartFile:null,
null!=multipartFile?multipartFile.getOriginalFilename():file.getName(),"true","true");
return JSONObject.parseObject(post, AnnexInfo.class);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 以post方式调用第三方接口,以form-data 形式 发送 MultipartFile 文件数据
*
* @param url post请求url
* @param fileParamName 文件参数名称
* @param multipartFile 文件
* @param paramMap 表单里其他参数
* @return 响应结果
*/
public static JSONObject doPostFormData(String url, String fileParamName, MultipartFile multipartFile, Map<String, Object> paramMap) {
// 创建Http实例
CloseableHttpClient httpClient = HttpClients.createDefault();
JSONObject jsonResult = null;
// 创建HttpPost实例
HttpPost httpPost = new HttpPost(url);
// 请求参数配置
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000)
.setConnectionRequestTimeout(10000).build();
httpPost.setConfig(requestConfig);
try {
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setCharset(StandardCharsets.UTF_8);
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
String fileName = multipartFile.getOriginalFilename();
// 文件流
builder.addBinaryBody("file", multipartFile.getInputStream(), ContentType.MULTIPART_FORM_DATA, fileName);
//表单中其他参数
for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
builder.addPart(entry.getKey(), new StringBody((String) entry.getValue(), ContentType.create("text/plain", Consts.UTF_8)));
}
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
httpPost.setHeader("token",getToken());
// 执行提交
HttpResponse response = httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
// 返回
String s = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
jsonResult = JSONObject.parseObject(s);
return jsonResult;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (httpClient != null) {
try {
httpClient.close();
} catch (IOException e) {
}
}
}
return null;
}
private static String POST(String url, InputStream inputStream, MultipartFile multipartFile, String name,String noRestrict,String useOriginalFilename) {
String body = null;
try {
body = HttpRequest.post(url).timeout(900000)
.header("token",getToken())
.header("content-type","application/x-www-form-urlencoded")
.form("file", new InputStreamResource(null!=inputStream?inputStream:multipartFile.getInputStream(),name))
.form("noRestrict",noRestrict)
.form("useOriginalFilename",useOriginalFilename)
.execute().body();
} catch (IOException e) {
throw new RuntimeException(e);
}
return body;
}
private static String getToken() {
Date date = new Date();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String dateStr = format.format(date);
String token= "d5a672629059998e9e8b_" + AES.encrypt(dateStr);
System.out.println(token);
return token;
}
public static void downloadUrlForResponse(String fileURL, HttpServletResponse response) {
OutputStream outputStream = null;
InputStream in = null;
try {
// 创建URL对象
URL url = new URL(fileURL);
// 打开连接
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
// 设置请求方法为GET
httpConn.setRequestMethod("GET");
// 获取响应码,200表示成功
int responseCode = httpConn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
// 获取输入流
in = httpConn.getInputStream();
// 构建保存文件的路径
String fileName = "";
String disposition = httpConn.getHeaderField("Content-Disposition");
String contentType = httpConn.getContentType();
int contentLength = httpConn.getContentLength();
if (disposition != null) {
// extracts file name from header field
int index = disposition.indexOf("filename=");
if (index > 0) {
fileName = disposition.substring(index + 10,
disposition.length() - 1);
}
} else {
// extracts file name from URL
fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1, fileURL.length());
}
response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
response.setContentType("application/octet-stream"); // 通用的二进制数据类型
outputStream = response.getOutputStream();
byte[] buffer = new byte[1024]; // 缓冲区大小,可以根据实际情况调整
int bytesRead;
// 循环读取输入流中的数据并写入到输出流
while ((bytesRead = in.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
// 刷新输出流,确保所有缓冲的数据都已写出
outputStream.flush();
System.out.println("File downloaded successfully.");
} else {
System.out.println("No file to download. Server replied HTTP code: " + responseCode);
}
httpConn.disconnect();
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
} finally {
try {
outputStream.close();
in.close();
} catch (Exception e) {
}
}
}
public static void downloadFile(String fileURL, String saveDir) {
try {
// 创建URL对象
URL url = new URL(fileURL);
// 打开连接
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
// 设置请求方法为GET
httpConn.setRequestMethod("GET");
// 获取响应码,200表示成功
int responseCode = httpConn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
// 获取输入流
InputStream in = httpConn.getInputStream();
// 构建保存文件的路径
String fileName = "";
String disposition = httpConn.getHeaderField("Content-Disposition");
String contentType = httpConn.getContentType();
int contentLength = httpConn.getContentLength();
if (disposition != null) {
// extracts file name from header field
int index = disposition.indexOf("filename=");
if (index > 0) {
fileName = disposition.substring(index + 10,
disposition.length() - 1);
}
} else {
// extracts file name from URL
fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1, fileURL.length());
}
// 构造保存文件的完整路径
Path saveFilePath = Paths.get(saveDir, fileName);
// 创建输出流
try (OutputStream out = Files.newOutputStream(saveFilePath)) {
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
}
System.out.println("File downloaded successfully.");
} else {
System.out.println("No file to download. Server replied HTTP code: " + responseCode);
}
httpConn.disconnect();
} catch (MalformedURLException e) {
System.out.println("Error: Invalid URL " + fileURL);
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
@AllArgsConstructor
@NoArgsConstructor
@Data
@Builder
public static class AnnexInfo {
private Integer code;
private String msg;
private String originalFilename;
private String fileName;
private String saveName;
private String ex;
private String url;
}
// AES加解密
private static class AES {
private static final String ALGORITHM = "AES";
private static final byte[] keyValue = "Lhzx1234Lhzx1234".getBytes();
public static String encrypt(String valueToEnc) {
try {
Key key = generateKey();
Cipher c = Cipher.getInstance(ALGORITHM);
c.init(Cipher.ENCRYPT_MODE, key);
byte[] encValue = c.doFinal(valueToEnc.getBytes(StandardCharsets.UTF_8));
// 可选地,对加密后的字节进行Base64编码以便于文本显示和传输
String encryptedValue = Base64.getEncoder().encodeToString(encValue);
return encryptedValue;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static String decrypt(String encryptedValue) {
try {
Key key = generateKey();
Cipher c = Cipher.getInstance(ALGORITHM);
c.init(Cipher.DECRYPT_MODE, key);
// 先将Base64编码的字符串解码回字节数组
byte[] decordedValue = Base64.getDecoder().decode(encryptedValue);
byte[] decValue = c.doFinal(decordedValue);
String decryptedValue = new String(decValue, StandardCharsets.UTF_8);
return decryptedValue;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private static Key generateKey() {
try {
Key key = new SecretKeySpec(keyValue, ALGORITHM);
return key;
} catch (Exception e) {
}
return null;
}
}
}