本文主要是介绍【javaweb:servlet】客户端请求服务端进行文件下载的demonstration,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1、服务端DownloadServlet代码
package indi.response.content;import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;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 DownloadServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//1.获取文件名String filename=request.getParameter("filename");//2.告诉客户端将要下载的文件的类型response.setContentType(this.getServletContext().getMimeType(filename));//最重要//3.告诉客户端该文件不是直接解析而是以附件的形式打开(即下载)response.setHeader("Content-Disposition","attachment;filename="+filename);//最重要//4.获取文件的绝对路径String path=this.getServletContext().getRealPath("/download/"+filename);//5.获取输出流ServletOutputStream output = response.getOutputStream();//6.获取输入流InputStream in=new FileInputStream(path);//7.开始输出文件int len=0;byte[] buffer=new byte[1024];while((len=in.read(buffer))>0) {output.write(buffer,0, len);}in.close();output.close();}public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet(request, response);}
}
2.客户端html代码
<!DOCTYPE html>
<html><head><meta charset="UTF-8"><title>文件下载页面</title><style>div{border: 1px solid saddlebrown;margin: auto;text-align: center;}</style></head><body><div><h1>根据标签下载服务器中指定的文件</h1><a href="/WEB14_Response/download/a.flv">a.flv</a><br /><a href="/WEB14_Response/download/a.jpg">a.jpg</a><br /><a href="/WEB14_Response/download/a.mp3">a.mp3</a><br /><a href="/WEB14_Response/download/a.mp4">a.mp4</a><br /><a href="/WEB14_Response/download/a.txt">a.txt</a><br /><a href="/WEB14_Response/download/a.zip">a.zip</a><br /><h1>根据服务器端编码的方式指定的文件</h1><a href="/WEB14_Response/downloadServlet?filename=a.flv">a.flv</a><br /><a href="/WEB14_Response/downloadServlet?filename=a.jpg">a.jpg</a><br /><a href="/WEB14_Response/downloadServlet?filename=a.mp3">a.mp3</a><br /><a href="/WEB14_Response/downloadServlet?filename=a.mp4">a.mp4</a><br /><a href="/WEB14_Response/downloadServlet?filename=a.txt">a.txt</a><br /><a href="/WEB14_Response/downloadServlet?filename=a.zip">a.zip</a><br /></div></body>
</html>
这篇关于【javaweb:servlet】客户端请求服务端进行文件下载的demonstration的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!