servlet下载文件例子

简介: servlet下载文件例子

servlet下载文件例子


package com.test;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HSR extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //通过路径得到一个输入流
        String path =     this.getServletContext().getRealPath("/WEB-INF/classes/1.jpg");
        FileInputStream fis =  new FileInputStream(path);
        //创建字节输出流
        ServletOutputStream sos  = response.getOutputStream();
        //得到要下载的图片文件名
        String filename = path.substring(path.lastIndexOf("\\"+1));
        //告诉客户端需要下载图片(通过响应消息头)
        response.setHeader("content-disposition", "attachment;filename="+filename);
        //告诉客户端下载文件的类型
        response.setHeader("content-type", "image/jpeg");
        //执行输出操作
        int len = 1;
        byte[] b = new byte[1024];
        while((len=fis.read(b)) != -1){
            sos.write(b,0,len);
        }
        sos.close();
        fis.close();
    }
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request,response);
    }
}
目录
相关文章
|
7月前
|
前端开发 应用服务中间件 C++
使用Servlet实现表白墙网站(前后端互联)小项目,Mac的M1(没有setting)在哪里找到Setting页面,下载smart tomcat及smart tomcat的配置。(二)
使用Servlet实现表白墙网站(前后端互联)小项目,Mac的M1(没有setting)在哪里找到Setting页面,下载smart tomcat及smart tomcat的配置。
使用Servlet实现表白墙网站(前后端互联)小项目,Mac的M1(没有setting)在哪里找到Setting页面,下载smart tomcat及smart tomcat的配置。(二)
|
10天前
|
缓存 前端开发 Java
15:Servlet 3.0文件上传与下载-Java Web
15:Servlet 3.0文件上传与下载-Java Web
24 5
|
7月前
|
JSON 前端开发 JavaScript
使用Servlet实现表白墙网站(前后端互联)小项目,Mac的M1(没有setting)在哪里找到Setting页面,下载smart tomcat及smart tomcat的配置。(一)
使用Servlet实现表白墙网站(前后端互联)小项目,Mac的M1(没有setting)在哪里找到Setting页面,下载smart tomcat及smart tomcat的配置。
Servlet实现下载图片到本地
Servlet实现下载图片到本地
|
XML 应用服务中间件 Linux
Springmvc文件上传(servlet3.0)/下载(ssm)以及坑点
(补充:再linux服务器上可能没用创建文件的权限,那就需要找到文件夹给权限,比如我的chmod -R 777 /home/tomcat/apache-tomcat-default/webapps/food)
156 0
|
容器 应用服务中间件
|
Java
使用Servlet实现下载文件的功能
使用Servlet实现下载文件的功能 在前台有一个下载链接,比如   下载   使用Servlet实现下载:     import java.
1063 0