Java实现普通的文件下载


@GetMapping("/download")
public void dowload(HttpServletRequest request, HttpServletResponse response) {
    String filepath = "D:\\BaiduYunDownload\\项目_06-06Full HD.mp4";
    File file = new File(filepath);
    String name = file.getName();
    response.setCharacterEncoding("utf-8");

    //该响应是下载
    response.setContentType("application/x-download;");
    //设置下载文件名称
    response.addHeader("Content-Disposition", "attachment;filename="
            + name);
    //文件大小
    response.setHeader("Content-Length", "" + file.length());
    BufferedInputStream is = null;
    BufferedOutputStream os = null;
    try {
        is = new BufferedInputStream(new FileInputStream(file));
        os = new BufferedOutputStream(response.getOutputStream());

        byte[] context = new byte[1024];
        int read = 0;
        while ((read = is.read(context, 0, 1024)) != -1) {
            os.write(context, 0, read);
            os.flush();
        }
        os.flush();

        response.setStatus(200);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        if (os!=null){
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

声明:冰醋酸|版权所有,违者必究|如未注明,均为原创|本网站采用BY-NC-SA协议进行授权

转载:转载请注明原文链接 - Java实现普通的文件下载


一切随缘