• servlet 实现下载文件


    servlet:

    public class UpAndDownServlet extends HttpServlet {


    public void doPost(HttpServletRequest request, HttpServletResponse response)

    throws ServletException, IOException {

    response.setContentType("text/html");
    String type = request.getParameter("type");

    if("down".equals(type)){
    File file = new File("D:\test\44444.png");
    FileInputStream is = new FileInputStream(file);
    BufferedInputStream bs = new BufferedInputStream(is);
    ServletOutputStream os = response.getOutputStream();
    BufferedOutputStream bos = new BufferedOutputStream(os);
    String date = new SimpleDateFormat("yyyy-HH-dd").format(new Date());
    String fileName = date + ".jpg";
    response.setHeader("Content-Disposition", "attachment; filename="" + fileName + """);
    byte[] len = new byte[1024*2];
    int read = 0;
    while((read=is.read(len)) != -1){
    bos.write(len, 0, read);
    System.out.println("read---"+read);
    }
    bos.flush();
    bos.close();
    is.close();
    }

    }

    }


    怎样实现文件下载
    要实现文件下载,我们仅仅须要设置两个特殊的对应头,它们是什么头?假设文件名称带中文,该怎样解决?
    两个特殊的对应头:
    ----Content-Type:       application/octet-stream
    ----Content-Disposition: attachment;filename=aaa.zip
    比如:
    response.setContentType("image/jpeg");response.setHeader("Content- Disposition","attachment;filename=Bluehills.jpg");

    页面:
    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    %>

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <base href="<%=basePath%>">
        <title>down</title>
      </head>
      <body>
        <form action="servlet/UpAndDownServlet?type=down" method="post">
        <input type="submit" value="下载">
        </form>
      </body>
    </html>


  • 相关阅读:
    解决关于 在android studio 出现的 DELETE_FAILED_INTERNAL_ERROR Error while Installing APK 问题
    oracle 时间日期常用语句及函数
    微信小程序 网络请求之re.request 和那些坑
    微信小程序 网络请求之设置合法域名
    开发中常用js记录(三)
    oracle 锁表 and 解锁
    微信小程序 JS动态修改样式
    微信小程序 获得用户输入内容
    微信小程序 引用其他js里的方法
    微信JSAPI支付回调
  • 原文地址:https://www.cnblogs.com/bhlsheji/p/5103533.html
Copyright © 2020-2023  润新知