zoukankan      html  css  js  c++  java
  • java io 文件下载功能

    一.

    @RequestMapping(value = "/download/{filename}")

    public void downloadFile(HttpServletRequest request,HttpServletResponse response,

    @PathVariable(value = "filename") String filename)

    throws IOException {

    //获取项目路径

    String readPath = request.getServletContext().getRealPath("/");

    readPath = readPath.substring(0, readPath.lastIndexOf("\"));

    readPath = readPath.substring(0, readPath.lastIndexOf("\"));

    //文件绝对路径

    String picPath = readPath+File.separator+"pai"+File.separator+"attachmentSimple"+File.separator+"1"+File.separator + filename;

    File file = new File(picPath);

    if(!file.exists()){

    throw new RuntimeException("视频文件不存在!");

    }

    response.setContentType("application/force-download");// 设置强制下载不打开

    response.addHeader("Content-Disposition",

    "attachment;fileName=" + filename);// 设置文件名

    FileInputStream inputStream = new FileInputStream(file);

    ServletOutputStream out = response.getOutputStream();

    int b = 0;

    byte[] buffer = new byte[1024];

    while (b != -1){

    out.write(buffer,0,b);

    b = inputStream.read(buffer);

    }

    inputStream.close();

    out.close();

    out.flush();

    }

    }

    二.

    @RequestMapping("download")

    public void download(@RequestParam("id") String id,

    HttpServletRequest request, HttpServletResponse response){

    VideoInfo video = (VideoInfo) videoService.getObjectById(VideoInfo.class, id);

    String path = request.getServletContext().getRealPath(video.getRestorePath());

    File file = new File(path);

    if(!file.exists()){

    throw new RuntimeException("视频文件不存在!");

    }

    String fileName = video.getRestorePath().substring(video.getRestorePath().indexOf(File.separator)+1);

    response.setContentType("application/force-download");// 设置强制下载不打开

    response.addHeader("Content-Disposition",

    "attachment;fileName=" + fileName);// 设置文件名

    byte[] buffer = new byte[1024];

    FileInputStream fis = null;

    BufferedInputStream bis = null;

    try {

    fis = new FileInputStream(file);

    bis = new BufferedInputStream(fis);

    OutputStream os = response.getOutputStream();

    int i = bis.read(buffer);

    while (i != -1) {

    os.write(buffer, 0, i);

    i = bis.read(buffer);

    }

    } catch (Exception e) {

    e.printStackTrace();

    } finally {

    if (bis != null) {

    try {

    bis.close();

    } catch (IOException e) {

    e.printStackTrace();

    }

    }

    if (fis != null) {

    try {

    fis.close();

    } catch (IOException e) {

    e.printStackTrace();

    }

    }

    }

    }

  • 相关阅读:
    次小生成树(SST)
    传纸条(scrip)
    动态规划练习5
    动态规划练习4
    整数的lqp拆分
    [HNOI2002]跳蚤
    BZOJ1803: Spoj1487 Query on a tree III
    51nod-1526: 分配笔名
    51nod-1615: 跳跃的杰克
    BZOJ2588: Spoj 10628. Count on a tree
  • 原文地址:https://www.cnblogs.com/zhi-ming/p/10453161.html
Copyright © 2011-2022 走看看