一、目录结构:
二、servlet编写:Dowmn
package cn.xh.download.servlet;
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;
import org.apache.commons.io.IOUtils;
/**
* Servlet implementation class Download
*/
public class Download extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public Download() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String fname="F:/音乐/2.mp3";
//设置文件类型
String contentType=this.getServletContext().getMimeType(fname);
//设置下载时显示的名字
String contentDisposition="attachment;filename=yuuy.mp3";
//**一个文件流
FileInputStream fin=new FileInputStream(fname);
//**两个文件头 Cotent大写C也可
response.setHeader("content-Type", contentType);
response.setHeader("content-Disposition", contentDisposition);
ServletOutputStream fout=response.getOutputStream();
IOUtils.copy(fin, fout);
fout.close();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}
注意导包:commons-io.jar; spring中有