从网络下载文件以流文件的方式给到浏览器
package com.hengqin.life.face.util;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
@Slf4j
public class DownloadFileUtils {
public static void downloadFile(String path, String filename,
HttpServletRequest request, HttpServletResponse response) {
InputStream inputStream = null;
OutputStream out = null;
HttpURLConnection conn = null;
try {
URL url = new URL(path);
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(3 * 1000);
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
inputStream = conn.getInputStream();
out = response.getOutputStream();
response.addHeader("Content-Disposition", "attachment;filename="
+ new String(filename.replaceAll(" ", "").getBytes("utf-8"),
"iso8859-1"));
response.setContentType("application/octet-stream");
int b;
while ((b = inputStream.read()) != -1) {
out.write(b);
}
} catch (IOException e) {
log.error("网络报错{}",e);
} finally {
try {
inputStream.close();
out.close();
} catch (IOException e) {
log.error("关闭报错{}",e);
}
}
}
public static byte[] readInputStream(InputStream inputStream) throws IOException {
byte[] buffer = new byte[1024];
int len = 0;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while ((len = inputStream.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
bos.close();
return bos.toByteArray();
}
}