java实现文件下载功能(SmartUpload)
方法一:使用jsp实现:<span style="font-family:FangSong_GB2312;font-size:18px;"><%@ page contentType="text/html;charset=gb2312" %>
<%@page import="com.jspsmart.upload.SmartUpload"%>
<%@page import="com.jspsmart.upload.File"%>
<%
//新建一个SmartUpload对象
SmartUpload su = new SmartUpload();
//初始化
su.initialize(pageContext);
//设定contentDisposition为null以禁止浏览器自动打开文件,保证单击链接后是下载文件。若不设定,则下载的文件扩展名为doc时,浏览器将自动用word打开它。扩展名为pdf时,浏览器将用acrobat打开。
su.setContentDisposition(null);
//下载文件
su.downloadFile("WEB-INF/upload/11.rar");
//处理输出流问题
out.clear();
out = pageContext.pushBody();
%>
</span> 方法二:使用servlet 实现 :
package downloadFile;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DownloadFile extends HttpServlet {
protected void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
// 服务器相对路径
String path = req.getParameter("path");
// 服务器绝对路径
path = getServletContext().getRealPath("/") + path;
// 检查文件是否存在
File obj = new File(path);
if (!obj.exists()) {
res.setContentType("text/html;charset=GBK");
res.getWriter().print("指定文件不存在!");
return;
}
// 读取文件名:用于设置客户端保存时指定默认文件名
int index = path.lastIndexOf("\\"); // 前提:传入的path字符串以“\”表示目录分隔符
String fileName = path.substring(index + 1);
// 写流文件到前端浏览器
ServletOutputStream out = res.getOutputStream();
res.setHeader("Content-disposition", "attachment;filename=" + fileName);
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(new FileInputStream(path));
bos = new BufferedOutputStream(out);
byte[] buff = new byte;
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
} catch (IOException e) {
throw e;
} finally {
if (bis != null)
bis.close();
if (bos != null)
bos.close();
}
}
}web.xml 设置:
<servlet>
<servlet-name>DownloadFile</servlet-name>
<servlet-class>downloadFile.DownloadFile</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DownloadFile</servlet-name>
<url-pattern>/DownloadFile</url-pattern>
</servlet-mapping>
</web-app>
如果此Servlet命名为downloadFile,请求的URL为:http://localhost:8888/upload/DownloadFile?path=web.txt
总结: 第一种方法我使用的jsp文件处理,并且使用第三方控件,简单的几行代码就搞定了,第二种方法是使用java语言写的,而且下载的文件是中文命名的话,还会出现乱码的问题.从此可以看出,站在巨人的肩膀上的重要性.
页:
[1]