下载服务器上的文件的jsp

本文介绍了一个使用Java实现的服务器端文件下载功能,支持中文文件名和路径。通过设置HTTP响应头来实现文件的正确下载,并确保了文件内容的正确传输。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<%@ page import="java.io.*"%>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<%
	response.setCharacterEncoding("UTF-8");
	request.setCharacterEncoding("UTF-8");
	String filepath = new String(request.getAttribute("redirectUrl")
			.toString().getBytes("ISO-8859-1"), "UTF-8");
	System.out.println("============================" + filepath);
	if (filepath != null) {
		OutputStream os = null;
		FileInputStream fis = null;
		try {
			String file = filepath;
			if (!(new File(file)).exists()) {
		System.out.println("没有文件");
		return;
			}
			String filename = file
			.substring(file.lastIndexOf("\\") + 1);
			System.out.println("文件名为:" + filename);
			os = response.getOutputStream();
			response.setHeader("content-disposition",
			"attachment;filename="
			+ new String(filename.getBytes("GBK"),
					"ISO-8859-1"));
			response.setContentType("application/octet-stream");//八进制流 与文件类型无关
			byte temp[] = new byte[1024];
			fis = new FileInputStream(file);
			int n = 0;
			while ((n = fis.read(temp)) != -1) {
		os.write(temp, 0, n);
			}
		} catch (Exception e) {
			out.print("出错了");
		} finally {
			if (os != null)
		os.close();
			if (fis != null)
		fis.close();
		}
		out.clear();
		out = pageContext.pushBody();
	}
%>



用来下载服务器上的文件,支持中文文件名,路径

来源于百度来的某个文章

稍许更改




                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值