栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Servlet实现文件下载功能

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Servlet实现文件下载功能

本文实例为大家分享了Servlet实现文件下载的具体代码,供大家参考,具体内容如下

把文件目录直接暴露给用户是很不安全的。所以要用Servlet来做,而且这样做,文件的存储方式就更丰富了,可以是从文件系统上取来的,也可以是数据库中经过计算生成的,或者从其它什么稀奇古怪的地方取来的。

public class DownloadServlet extends HttpServlet {
  private String contentType = "application/x-msdownload";
  private String enc = "utf-8";
  private String fileRoot = "";


  
  public void init(ServletConfig config) throws ServletException {
    String tempStr = config.getInitParameter("contentType");
    if (tempStr != null && !tempStr.equals("")) {
      contentType = tempStr;
    }
    tempStr = config.getInitParameter("enc");
    if (tempStr != null && !tempStr.equals("")) {
      enc = tempStr;
    }
    tempStr = config.getInitParameter("fileRoot");
    if (tempStr != null && !tempStr.equals("")) {
      fileRoot = tempStr;
    }
  }

  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String filepath = request.getParameter("filepath");
    String fullFilePath = fileRoot + filepath;
    
    File file = new File(fullFilePath);
    
    if (file.exists()) {
      String filename = URLEncoder.encode(file.getName(), enc);
      response.reset();
      response.setContentType(contentType);
      response.addHeader("Content-Disposition", "attachment; filename="" + filename + """);
      int fileLength = (int) file.length();
      response.setContentLength(fileLength);
      
      if (fileLength != 0) {
 
 InputStream inStream = new FileInputStream(file);
 byte[] buf = new byte[4096];
 
 ServletOutputStream servletOS = response.getOutputStream();
 int readLength;
 while (((readLength = inStream.read(buf)) != -1)) {
   servletOS.write(buf, 0, readLength);
 }
 inStream.close();
 servletOS.flush();
 servletOS.close();
      }
    }
  }

web.xml

  
    downloadservlet-name>
    org.mstar.servlet.DownloadServletservlet-class>
    
      fileRootparam-name>
      d:/tempparam-value>
    init-param>
    
      contentTypeparam-name>
      application/x-msdownloadparam-value>
    init-param>
    
      encparam-name>
      utf-8param-value>
    init-param>
  servlet>
  
    downloadservlet-name>
    /downurl-pattern>
  servlet-mapping>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/142576.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号