下载文件
Posted qfdy123
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了下载文件相关的知识,希望对你有一定的参考价值。
package com.zy.down; import java.io.FileInputStream; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class FileDown */ @WebServlet("/FileDown") public class FileDown extends HttpServlet protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException String file = request.getParameter("file"); //客户端传递的需要下载的文件名 String path = request.getServletContext().getRealPath("/img")+"/"+file; //默认认为文件在当前项目的根目录 FileInputStream fis = new FileInputStream(path); response.setCharacterEncoding("utf-8"); //attachment 附件--有附件为下载,无附件为预览 response.setHeader("Content-Disposition", "attachment; filename="+file); ServletOutputStream out = response.getOutputStream(); byte[] bt = new byte[1024]; int length = 0; //边读边写 while((length=fis.read(bt))!=-1) out.write(bt,0,length); out.close(); protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException // TODO Auto-generated method stub doGet(request, response);
以上是关于下载文件的主要内容,如果未能解决你的问题,请参考以下文章