Java 实现图片或文件在线预览及下载

Java源码网 7月前 ⋅ 383 阅读 0 下载

Java 实现图片或文件在线预览及下载

效果图

打开图片

100.png

打开pdf

200.png

后端代码

@GetMapping("/downFile")
public void downFile(HttpServletResponse response, HttpServletRequest request) {
    try {
//            File file = new File("C:\\Users\\hnsh\\Pictures\\铁山靠.png");
        File file = new File("F:\\BaiduNetdiskDownload\\activiti教程 (1).pdf");
        String filename = file.getName();
        String fileType = filename.substring(filename.indexOf(".") + 1);

        // 以流的形式下载文件。
        FileInputStream fileInputStream = new FileInputStream(file);
        InputStream fis = new BufferedInputStream(fileInputStream);
        byte[] buffer = new byte[1024];
        int len = 0;
        // 清空response
        response.reset();
        // 设置response的Header
        // 解决跨域
        response.addHeader("Access-Control-Allow-Origin", "*");
        boolean b = "jpg".equalsIgnoreCase(fileType) || "png".equalsIgnoreCase(fileType) || "gif".equalsIgnoreCase(fileType);
        // 图片预览
        if (b) {
            response.setContentType("image/" + fileType);
        } else if ("pdf".equalsIgnoreCase(fileType)) {
            // pdf 预览
            response.setContentType("application/pdf");
        } else {
            // 直接下载
            response.setContentType("application/text;chartset=utf-8");
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
            response.addHeader("Content-Length", "" + file.length());
        }
        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
        int a = 0;
        while ((len = fis.read(buffer)) != -1) {
            a = len + a;
            toClient.write(buffer, 0, len);
        }
        toClient.flush();
        toClient.close();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

温馨提示:setContentType的值决定打开地址的文件或者图片是直接下载还在线预览。

References

[1] https://blog.csdn.net/weixin_38977885/article/details/119573659


全部评论: 0

    我有话说: