//本次的文件下载是接着上次文件上传的
//为方便实现文件下载,可借助第三方开源jar包:commons.io;
//因为下载时候与浏览器类型有一定关系,可能会出现一些小偏差
//客户端代码:<a href="<c:url value=‘/DownloadServlet‘/>">点击下载</a>
//以下为服务端代码:
package cn.hl.download;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
public class DownloadServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
/*
* 请求头设置与下载流
* 1. Content-Type
* 2. Content-Disposition
* 3. 下载流:下载文件
*/
String filename="D:/Finally Found Ya.mp3";//楼主的例子为D盘下的一首mp3(要下载的内容)
String framename = new String("Finally Found Ya.mp3".getBytes("GBK"), "utf-8");//设置编码格式
String contentType=this.getServletContext().getMimeType(filename);//通过文件名称获取MIME类型
String contentDisposition ="attachment;filename="+framename;//激活文件下载框
FileInputStream in=new FileInputStream(filename);
response.setHeader("Content-Type", contentType);
response.setHeader("Content-Disposition", contentDisposition);
ServletOutputStream out=response.getOutputStream();
IOUtils.copy(in, out);
in.close();
}