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

servlet下载文件实现代码详解(五)

程序员文章站 2024-04-03 17:30:28
本文实例为大家分享了servlet下载文件的具体代码,供大家参考,具体内容如下 1.servlet下载文件   servlet下载文件就是将服务器端的文件传输到客户端。...

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

1.servlet下载文件

  servlet下载文件就是将服务器端的文件传输到客户端。

2案例

下载文件servlet类

package com.learn;

import javax.servlet.servletconfig;
import javax.servlet.servletexception;
import javax.servlet.http.httpservlet;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;
import java.io.file;
import java.io.ioexception;
import java.io.inputstream;
import java.io.outputstream;

/**
 * created by administrator on 2017/09/24.
 */
public class downloadservlet extends httpservlet {
  private string filepath;

  @override
  public void init(servletconfig config) throws servletexception {
    super.init(config);
    filepath = config.getinitparameter("filepath");
    //初始化路径
    //filepath = config.getservletcontext().getrealpath(filepath);
    system.out.println("初始化文件路径:"+filepath);
  }

  @override
  protected void doget(httpservletrequest req, httpservletresponse resp) throws servletexception, ioexception {
    dopost(req,resp);

  }

  @override
  protected void dopost(httpservletrequest req, httpservletresponse resp) throws servletexception, ioexception {

    outputstream out; //输出流
    inputstream in; //输入流

    string filename = req.getparameter("filename");
    system.out.println("文件名称:"+filename);
    //如果把文件名为null则提示用户
    if(filename == null){
      out = resp.getoutputstream();
      out.write("please input filename".getbytes());
      out.close();
    }
    //获取文件流
    in = getservletcontext().getresourceasstream(filepath+ file.separator+filename);
    system.out.println(in==null?true:false);
    int length = in.available();
    
    //设置返回消息头部信息
    resp.setcontenttype("application/force-download");
    resp.setheader("content-length",string.valueof(length));
    resp.setheader("content-disposition","attachment;filename=\""+filename+"\"");
    //输出文件到客户端
    out = resp.getoutputstream();
    int bytesend = 0 ;
    byte[] buff = new byte[512];
    while ((bytesend = in.read(buff))!= -1){
      out.write(buff,0,bytesend);
    }
    in.close();
    out.close();
  }
}

web.xml配置

 <servlet>
  <servlet-name>download</servlet-name>
  <servlet-class>com.learn.downloadservlet</servlet-class>
  <init-param>
    <param-name>filepath</param-name>
    <param-value>file</param-value>
  </init-param>
 </servlet>
 <servlet-mapping>
  <servlet-name>download</servlet-name>
  <url-pattern>/download</url-pattern>
 </servlet-mapping>