zoukankan      html  css  js  c++  java
  • javaWeb之文件下载

    //本次的文件下载是接着上次文件上传的

    //为方便实现文件下载,可借助第三方开源jar包:commons.io;

    //因为下载时候与浏览器类型有一定关系,可能会出现一些小偏差

    //客户端代码:<a href="<c:url value='/DownloadServlet'/>">点击下载</a>

    //以下为服务端代码:

    package cn.hl.download;

    import java.io.FileInputStream;
    import java.io.IOException;
    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;
    import org.apache.commons.io.IOUtils;

    public class DownloadServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    request.setCharacterEncoding("utf-8");
    response.setContentType("text/html;charset=utf-8");
    /*
    * 请求头设置与下载流
    * 1. Content-Type
    * 2. Content-Disposition
    * 3. 下载流:下载文件
    */
    String filename="D:/Finally Found Ya.mp3";//楼主的例子为D盘下的一首mp3(要下载的内容)

    String framename = new String("Finally Found Ya.mp3".getBytes("GBK"), "utf-8");//设置编码格式

    String contentType=this.getServletContext().getMimeType(filename);//通过文件名称获取MIME类型
    String contentDisposition ="attachment;filename="+framename;//激活文件下载框
    FileInputStream in=new FileInputStream(filename);

    response.setHeader("Content-Type", contentType);
    response.setHeader("Content-Disposition", contentDisposition);

    ServletOutputStream out=response.getOutputStream();
    IOUtils.copy(in, out);
    in.close();
    }

  • 相关阅读:
    LiveCD 是指用光盘就能启动并运行的系统
    漂亮的代码配色方案
    编程语言基础知识梗概
    监听器在游戏开发中的应用消息回调
    游戏业现状
    PS 1.x 中的寄存器
    Irrlicht(鬼火引擎)中多设备的支持
    关于《3D管线导论》这本书
    D3DPOOL
    c++虚函数表探究
  • 原文地址:https://www.cnblogs.com/fcbmers/p/5425077.html
Copyright © 2011-2022 走看看