您的位置:首页 > 编程语言 > Java开发

JAVA根据文件名、URL下载远程文件

2016-09-28 15:21 453 查看
/**
* 文件转换为流返回
*
* @param response
* @param filePath
* @param fileName
* @throws IOException
*/
private static void imageDownload(final HttpServletResponse response, String filePath, String fileName) throws IOException {
byte[] data = toByteArray(filePath);
fileName = URLEncoder.encode(fileName, "UTF-8");
response.reset();
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
response.addHeader("Content-Length", "" + data.length);
response.setContentType("image/jpeg;charset=UTF-8");
OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
outputStream.write(data);
outputStream.flush();
outputStream.close();
response.flushBuffer();
}

/**
* 读取到字节数组2
*
* @param filePath
* @return
* @throws IOException
*/
private static byte[] toByteArray(String filePath) throws IOException {
InputStream inputStream = null;
ByteArrayOutputStream outStream = null;
try {
URL url = new URL(filePath);
HttpURLConnection uc = (HttpURLConnection) url.openConnection();
uc.setDoInput(true);// 设置是否要从 URL 连接读取数据,默认为true
uc.connect();
inputStream = uc.getInputStream();
outStream = new ByteArrayOutputStream(uc.getContentLength());
byte[] temp = new byte[uc.getContentLength()];
int size = 0;
while ((size = inputStream.read(temp)) != -1) {
outStream.write(temp, 0, size);
}
byte[] content = outStream.toByteArray();
inputStream.close();
outStream.close();
return content;
} catch (IOException e) {
e.printStackTrace();
throw e;
} finally {
try {
if (outStream != null) {
outStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java