java服务器下载jpg等静态资源方法

本文介绍如何使用Java服务器向浏览器提供jpg等静态文件的下载服务,详细阐述了实现这一功能的方法和步骤。

浏览器下载服务器上jpg等静态资源方法



	/**
	 * 服务器下载静态文件
	 * @param request
	 * @param response
	 * @param filePath
	 * @param fileName
	 * @throws Exception
	 */
	public static void browserDownloadFile(HttpServletRequest request, HttpServletResponse response, String filePath, String fileName) throws Exception {
		File downloadFile = new File(filePath, fileName);
		if (!downloadFile.exists() || !downloadFile.isFile()) {
			throw new Exception("文件不存在!");
		}
		
		String userAgent = request.getHeader("User-Agent").toLowerCase();
		if (userAgent.indexOf("firefox") > -1) { //火狐浏览器
			fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
			response.setHeader("content-disposition", String.format("attachment; filename=\"%s\"", fileName));
		} else {
			response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8")); 
		}

		InputStream in = null;
		OutputStream out = null;
		try {
			in = new FileInputStream(downloadFile.getAbsolutePath()); // 获取文件的流
			int len = 0;
			byte buf[] = new byte[1024];// 缓存作用
			out = response.getOutputStream();// 输出流
			while ((len = in.read(buf)) > 0) { // 切忌这后面不能加 分号 ”;“
				out.write(buf, 0, len);// 向客户端输出,实际是把数据存放在response中,然后web服务器再去response中读取
			}
		} finally {
			if (out != null) {
				try {
					out.flush();
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值