Servlet&Jsp 下载代码备用

package demo;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoadFile extends HttpServlet{

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		OutputStream output=resp.getOutputStream();
		byte []b=new byte[1024];
		
		File file=new File("c:\\temp","test.zip");
		// the dialogbox of download file.
	    resp.setHeader("Content-disposition", "attachment;filename="
	              + "test.rar");
	    resp.setContentType("application/x-tar");
	    long fileLength=file.length();
	    String length=String.valueOf(fileLength);
	    resp.setHeader("Content_Length", length);
	    FileInputStream input=new FileInputStream(file);
	    int n=0;
	    while((n=input.read(b))!=-1){
	    	output.write(b, 0, n);
	    }
		input.close();
		output.close();
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		super.doPost(req, resp);
	}

	
}

你可能感兴趣的:(servlet)