欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Servlet实现文件下载功能

程序员文章站 2024-02-19 20:46:46
本文实例为大家分享了servlet实现文件下载的具体代码,供大家参考,具体内容如下 把文件目录直接暴露给用户是很不安全的。所以要用servlet来做,而且这样做,文件的存...

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

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

public class downloadservlet extends httpservlet {
  private string contenttype = "application/x-msdownload";
  private string enc = "utf-8";
  private string fileroot = "";


  /**
   * 初始化contenttype,enc,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);
      /*如果文件长度大于0*/
      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

  <servlet>
    <servlet-name>downloadservlet-name>
    <servlet-class>org.mstar.servlet.downloadservletservlet-class>
    <init-param>
      <param-name>filerootparam-name>
      <param-value>d:/tempparam-value>
    init-param>
    <init-param>
      <param-name>contenttypeparam-name>
      <param-value>application/x-msdownloadparam-value>
    init-param>
    <init-param>
      <param-name>encparam-name>
      <param-value>utf-8param-value>
    init-param>
  servlet>
  <servlet-mapping>
    <servlet-name>downloadservlet-name>
    <url-pattern>/downurl-pattern>
  servlet-mapping>

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