说明
- 网络文件URL 转 Base64字符串
- Base64字符串 转 本地文件
- 根据URL下载网络
示例代码
package com.util;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.util.UriUtils;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
public class FileTest {
private static Logger log = LoggerFactory.getLogger(FileUtil.class);
public static String fileToBase64(String fileUrl) {
if (StringUtils.isEmpty(fileUrl)) {
log.info("[fileToBase64] fileUrl参数为空");
return "";
}
fileUrl = fileUrl.replaceAll("\\\\", "/");
URL url = null;
InputStream is = null;
ByteArrayOutputStream outStream = null;
HttpURLConnection httpURLConnection = null;
try {
url = new URL(fileUrl);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.connect();
if (httpURLConnection.getResponseCode() != HttpURLConnection.HTTP_OK) {
log.error("[fileToBase64] 连接失败/链接失效/文件不存在 ");
return "";
}
is = httpURLConnection.getInputStream();
outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
if (is != null) {
is.close();
}
if (outStream != null) {
outStream.close();
}
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
log.info("[fileToBase64] 文件转base64字符串成功");
return new BASE64Encoder().encode(outStream.toByteArray());
} catch (Exception ex) {
log.error("[fileToBase64] 文件转base64字符串异常: " + ex.toString());
ex.printStackTrace();
return "";
}
}
public static String base64ToFile(String base64, String path) {
if (StringUtils.isBlank(base64) || StringUtils.isBlank(path)) {
log.error("[base64ToFile] 参数为空 ");
return "";
}
BASE64Decoder decoder = new BASE64Decoder();
OutputStream out = null;
try {
File file = new File(path);
File fileParent = file.getParentFile();
if (!fileParent.exists()) {
fileParent.mkdirs();
}
file.createNewFile();
byte[] b = decoder.decodeBuffer(base64);
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {
b[i] += 256;
}
}
out = new FileOutputStream(path);
out.write(b);
out.flush();
out.close();
log.info("[base64ToFile] base64转文件成功");
return path;
} catch (Exception ex) {
ex.printStackTrace();
log.error("[base64ToFile] base64字符串转文件异常: " + ex.toString());
return "";
}
}
public static String downloadHttpFile(String url, String path) {
try {
URL urlPath = new URL(UriUtils.encodePath(url, "UTF-8"));
File file = new File(path);
File fileParent = file.getParentFile();
if (!fileParent.exists()) {
fileParent.mkdirs();
}
file.createNewFile();
FileUtils.copyURLToFile(urlPath, new File(path));
log.info("[downloadHttpFile] 根据URL下载文件成功");
return "";
} catch (IOException ex) {
ex.printStackTrace();
log.error("[downloadHttpFile] 根据URL下载文件异常: " + ex.toString());
return "";
}
}
public static void downLoadFile(String url, String path) {
InputStream inputStream = null;
FileOutputStream outputStream = null;
HttpURLConnection conn = null;
ByteArrayOutputStream byteOutputStream = null;
try {
URL urlPath = new URL(url);
conn = (HttpURLConnection) urlPath.openConnection();
conn.setConnectTimeout(3 * 1000);
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
inputStream = conn.getInputStream();
byte[] buffer = new byte[1024];
int len = 0;
byteOutputStream = new ByteArrayOutputStream();
while ((len = inputStream.read(buffer)) != -1) {
byteOutputStream.write(buffer, 0, len);
}
File file = new File(path);
File fileParent = file.getParentFile();
if (!fileParent.exists()) {
fileParent.mkdirs();
}
file.createNewFile();
outputStream = new FileOutputStream(file);
outputStream.write(byteOutputStream.toByteArray());
if (outputStream != null) {
outputStream.close();
}
if (byteOutputStream != null) {
byteOutputStream.close();
}
if (inputStream != null) {
inputStream.close();
}
if (conn != null) {
conn.disconnect();
}
} catch (IOException ex) {
ex.printStackTrace();
log.error("[downLoadFile] 从网络Url中下载文件 异常" + ex.toString());
}
}
public static void main(String[] args) {
String imageUrl = "http://10.2.0.1:8083/image/nj.jpg";
String base64 = fileToBase64(imageUrl);
System.out.println(base64);
base64ToFile(base64, "D:\\image\\test.jpg");
downloadHttpFile(imageUrl, "D:\\image\\test2.jpg");
String pdfUrl = "http://10.2.0.1:8083/image/test.pdf";
String base642 = fileToBase64(pdfUrl);
System.out.println(base642);
base64ToFile(base642, "D:\\image\\11.pdf");
downLoadFile(pdfUrl, "D:\\image\\22.pdf");
}
}