java的文件下载、预览、与byte数组互转

文件下载、预览
点击跳转
文件与byte数组互转
点此跳转
文件下载后,删除目录和文件
点此跳转

以上是参考博客

public void downloadFile(String id, HttpServletResponse res) {
        try {
            // 获取文件名
            String fileName = faSysIgnoreMapper.getFileName(id);
            // 下载文件
            byte[] bytes = remoteFastdfsService.downloadFile(id).getData();
            if (null == bytes){
                res.sendError(404, "File not found or empty!");
                return;
            }
            // 生成临时目录路径
            String dirPath = FampConfig.PATHCONFIG_TEMPPATH + File.separator + UUID.randomUUID().toString();
            File dir = new File(dirPath);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            // 文件路径
            String filePath = dirPath + File.separator + fileName;
            File file = new File(filePath);
            // byte转文件
            FileOutputStream fos = new FileOutputStream(file);
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            bos.write(bytes);
            fos.close();
            bos.close();
            // 下载文件到浏览器
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
            byte[] buf = new byte[1024];
            int len = 0;
            res.reset(); // 非常重要
            if (false) { // 在线打开方式  预览
                URL u = new URL("file:///" + filePath);
                res.setContentType(u.openConnection().getContentType());
                res.setHeader("Content-Disposition", "inline; filename=" + file.getName());
                // 文件名应该编码成UTF-8
            } else { // 纯下载方式
                res.setContentType("application/x-msdownload");
                res.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(file.getName(), "UTF-8"));
            }
            OutputStream out = res.getOutputStream();
            while ((len = bis.read(bytes)) > 0)
                out.write(bytes, 0, len);
            bis.close();
            out.close();
            file.delete();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

实现了pdf的下载和预览、删除,还没有测试图片及其他文件。

什么是数据流
数据流是指所有的数据通信通道
有两类流,InputStream and OutputStream,Java中每一种流的基本功能依赖于它们。
InputStream 用于read,
OutputStream 用于write,
读和写都是相对与内存说的,读就是从其他地方把数据拿进内存,写就是把数据从内存推出去。
这两个都是抽象类,不能直接使用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值