一:单纯jsp+servlet实现下载(通过测试)
servlet后台:
package fileOperate;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
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 do_download extends HttpServlet {
/**
* Constructor of the object.
*/
public do_download() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//第一种下载方式
response.setContentType("application/x-download");
// String filenamedownload ="/upload/1.jpg";//相对路径
String filenamedisplay="1.jpg";
filenamedisplay=java.net.URLEncoder.encode(filenamedisplay, "UTF-8");
response.setHeader("Content-disposition", "attachment;filename-"+filenamedisplay);
// try
// {
// RequestDispatcher rd = request.getRequestDispatcher(filenamedownload);
// if(rd!=null)
// {
// rd.forward(request,response);
// }
// response.flushBuffer();
// }
// catch(Exception e)
// {
// System.out.println(e.getMessage());
// }
//第二种下载
String filenamedownload ="C:/Program Files/Apache Software Foundation/Tomcat 5.0/webapps/fileOperate/upload/1.jpg";
InputStream is=null;
ServletOutputStream sos=null;
try
{
is=new FileInputStream(filenamedownload);
sos=response.getOutputStream();
byte[] buff=new byte[2048];
int byteRead;
while(-1!=(byteRead=is.read(buff,0,buff.length)));
{
sos.write(buff,0,byteRead);
sos.flush();
}
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
finally
{
if(sos!=null)
{
sos.close();
}
if(is!=null)
{
is.close();
}
}
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occure
*/
public void init() throws ServletException {
// Put your code here
}
}
二:单纯struts1实现上传下载
代码附件:上传下载