温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Servlet实现文件下载功能

发布时间:2020-08-29 13:41:45 来源:脚本之家 阅读:115 作者:两颗番茄 栏目:编程语言

本文实例为大家分享了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>

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

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI