服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|JAVA教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|JavaScript|易语言|

服务器之家 - 编程语言 - JAVA教程 - servlet下载文件实现代码详解(五)

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

2021-01-14 15:46柳暗花明睡一觉 JAVA教程

这篇文章主要为大家详细介绍了servlet下载文件的实现代码,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

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

1.servlet下载文件

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

2案例

下载文件servlet类

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
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配置

?
1
2
3
4
5
6
7
8
9
10
11
12
<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>
 

原文链接:http://www.cnblogs.com/wwyx-xi/p/7588503.html

延伸 · 阅读

精彩推荐