|
@@ -1,10 +1,16 @@
|
|
|
package cn.com.qmth.examcloud.commons.util;
|
|
|
|
|
|
+import okhttp3.Request;
|
|
|
+import okhttp3.Response;
|
|
|
+import okhttp3.ResponseBody;
|
|
|
import org.apache.commons.lang3.StringUtils;
|
|
|
import org.slf4j.Logger;
|
|
|
import org.slf4j.LoggerFactory;
|
|
|
|
|
|
+import java.io.BufferedOutputStream;
|
|
|
import java.io.File;
|
|
|
+import java.io.FileOutputStream;
|
|
|
+import java.io.IOException;
|
|
|
import java.text.SimpleDateFormat;
|
|
|
import java.util.Arrays;
|
|
|
import java.util.Comparator;
|
|
@@ -129,4 +135,48 @@ public class FileUtil {
|
|
|
return new SimpleDateFormat("yyMMddHHmmssSSS").format(new Date()) + xyz;
|
|
|
}
|
|
|
|
|
|
+ public static void saveToFile(byte[] bytes, File targetFile) {
|
|
|
+ if (bytes == null || targetFile == null) {
|
|
|
+ return;
|
|
|
+ }
|
|
|
+
|
|
|
+ if (!targetFile.exists()) {
|
|
|
+ try {
|
|
|
+ targetFile.getParentFile().mkdirs();
|
|
|
+ targetFile.createNewFile();
|
|
|
+ } catch (IOException e) {
|
|
|
+ log.error(e.getMessage(), e);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ try (FileOutputStream fos = new FileOutputStream(targetFile);
|
|
|
+ BufferedOutputStream bos = new BufferedOutputStream(fos);) {
|
|
|
+ bos.write(bytes);
|
|
|
+ } catch (IOException e) {
|
|
|
+ log.error(e.getMessage(), e);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ public static void saveImageToFile(String imgUrl, String filePath) {
|
|
|
+ byte[] data = null;
|
|
|
+ Request request = new Request.Builder().url(imgUrl).get().build();
|
|
|
+
|
|
|
+ try (Response response = OKHttpUtil.getOkHttpClient().newCall(request).execute();) {
|
|
|
+ if (response.isSuccessful()) {
|
|
|
+ ResponseBody body = response.body();
|
|
|
+ if (body != null) {
|
|
|
+ data = body.bytes();
|
|
|
+ }
|
|
|
+ }
|
|
|
+ } catch (Exception e) {
|
|
|
+ log.error(e.getMessage(), e);
|
|
|
+ }
|
|
|
+
|
|
|
+ if (data == null || data.length == 0) {
|
|
|
+ throw new RuntimeException("图片下载错误!" + imgUrl);
|
|
|
+ }
|
|
|
+
|
|
|
+ saveToFile(data, new File(filePath));
|
|
|
+ }
|
|
|
+
|
|
|
}
|