前面有介绍过文件传输的实现,今天来教教大家如何实现网页上的文件下载功能~
仅谈文件传输的话,这与javaSE中学的IO流如出一辙,换汤不换药罢了.
以下为本次小课题的代码实现:
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;
public class Test extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//通过路径得到一个输入流
String path = this.getServletContext().getRealPath("/WEB-INF/classes/sourse/photo.jpg");
FileInputStream fis = new FileInputStream(path);
//创建字节输出流
ServletOutputStream sos = response.getOutputStream();