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利用SMB上传、下载、读取(内容或文件名)、复制、删除远程文件
- Android里根据下载文件的url获取文件名
- JAVA 根据Url把多文件打包成ZIP下载实例
- java根据URL地址下载文件
- android:根据下载文件的url获取文件名
- JAVA 根据Url把多文件打包成ZIP下载
- Java通过URL下载网络文件,获取文件流并修改文件名
- java网络编程____使用url下载远程文件(图片,软件等)
- java.net.URL请求远程文件下载
- JAVA根据文件存放的url路径,ZIP压缩并下载
- java web应用文件下载(包括中文文件名乱码处理)
- JAVA 文件下载时的文件名乱码解决
- tomcat下载文件时,URL含有文字参数与空格参数出错(java.io.FileNotFoundException错误) 解决方法(转)
- java 通过 URL 类和 URLConnection类 以及输入流实现文件下载功能
- org.apache.commons.net.ftp.FTPClient----根据文件名,路径检索文件 FTP上传 下载 删除文件
- java 根据url下载图片保存到本地
- Java访问Url地址并下载文件
- Java实现文件下载并解决中文文件名乱码
- Java实现跨域文件下载(下载远程文件)
- java文件下载程序中,解决汉字文件名乱码