java实现文件下载,批量下载,文件在线预览,word转pdf,excel转pdf

pdf,excel转word所需jar包  网盘链接  提取码:4gmw

目录

1.在resources下新建license.xml

2.文件转换工具类

3.文件下载 

4.批量下载

5.在线打开文件 



1.在resources下新建license.xml

 Tips:这个文件好像是去除水印需要的东西,word转pdf不需要,excel转pdf时需要用到(可能这个jar版本有点低)

<License>
    <Data>
        <Products>
            <Product>Aspose.Total for Java</Product>
            <Product>Aspose.Excel for Java</Product>
        </Products>
        <EditionType>Enterprise</EditionType>
        <SubscriptionExpiry>20991231</SubscriptionExpiry>
        <LicenseExpiry>20991231</LicenseExpiry>
        <SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>
    </Data>
    <Signature>
        sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=
    </Signature>
</License>

2.文件转换工具类

因为浏览器不支持打开word文档以及excel文件,也不能单独给服务器装个其他插件来在线打开,所以就决定先转换成pdf然后再用浏览器打开(doc,docx,wps,xls,xlsx这些我都替小伙伴们试过啦,木的问题,其他类型的大家可以再研究研究)

import com.aspose.cells.License;
import com.aspose.cells.PdfSaveOptions;
import com.aspose.cells.Workbook;
import com.aspose.words.Document;
import com.aspose.words.SaveFormat;
import lombok.extern.slf4j.Slf4j;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;

@Slf4j
public class FileUtils {
 
    /**
     * Word 转换  Pdf
     * @param fileFullPath  旧文件全路径   /home/2022-07/保密协议.docx

     */
    public static String doc2pdf(String fileFullPath) {
        try {
            //    ----->   /home/2022-07/
            String path = fileFullPath.substring(0, fileFullPath.lastIndexOf("/")+1);
            //    ----->保密协议
            String fileName=fileFullPath.substring(fileFullPath.lastIndexOf("/")+1,fileFullPath.lastIndexOf("."));
            String outFIleFullPath=path+fileName+".pdf";
            File file = new File(outFIleFullPath); // 新建一个pdf文档
            FileOutputStream os = new FileOutputStream(file);
            /** 这里需要指定Linux服务器上从本地windows上传的字体库,否则生成乱码
             *  【/usr/share/fonts/windowsFonts/】位于Linux服务器上的windows字体,作为word转pdf用
             */
            //FontSettings.getDefaultInstance().setFontsFolder("/usr/share/fonts/windowsFonts/", true);
            Document doc = new Document(fileFullPath);
            doc.save(os,SaveFormat.PDF);// 全面支持DOC, DOCX,wps
            os.close();
            return  outFIleFullPath;
        } catch (Exception e) {
            e.printStackTrace();
            log.info("pdf转换异常");
            return null;
        }
    }

    /**
     * excel 转换  Pdf
     * @param fileFullPath  旧文件全路径   /home/2022-07/保密协议.xlsx

     */
    public static String excel2pdf(String fileFullPath) {
        if (!getLicense()) {          // 验证License 若不验证则转化出的pdf文档会有水印产生
            return null;
        }
        try {
            String path = fileFullPath.substring(0, fileFullPath.lastIndexOf("/")+1);
            String fileName=fileFullPath.substring(fileFullPath.lastIndexOf("/")+1,fileFullPath.lastIndexOf("."));
            String outFIleFullPath=path+fileName+".pdf";
            File pdfFile = new File(outFIleFullPath); // 输出路径
            FileInputStream excelstream = new FileInputStream(fileFullPath);
            Workbook wb = new Workbook(excelstream);// excel路径,这里是先把数据放进缓存表里,然后把缓存表转化成PDF
            FileOutputStream fileOS = new FileOutputStream(pdfFile);
            PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
            pdfSaveOptions.setOnePagePerSheet(true);//参数true把内容放在一张PDF页面上;
            wb.save(fileOS, pdfSaveOptions);
            fileOS.close();
            return  outFIleFullPath;
        } catch (Exception e) {
            e.printStackTrace();
            log.info("excel转换异常");
            return null;
        }
    }
    public static boolean getLicense() {
        boolean result = false;
        try {
            InputStream is =
                    FileUtils.class
                            .getClassLoader()
                            .getResourceAsStream(
                                    "license.xml"); //
            // license.xml这个文件你放在静态文件资源目录下就行了
            License aposeLic = new License();
            aposeLic.setLicense(is);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static void main(String[] args) {
        FileUtils.doc2pdf("D:\\home\\2022-07\\保密协议.wps");
    }
}

3.文件下载 

Tips:下载的是本地文件,后续用了文件存储服务器后可能会改,还有个小问题,下载文件时    响应头    Content-Disposition   文件名称中文乱码 

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;



 /**
     * 文件下载
     *
     * @param filePath
     * @param response
     */
    public void downloadFile(String filePath, HttpServletResponse response, HttpServletRequest request) {
        InputStream fis = null;
        OutputStream out = null;
        try {
            // path是指欲下载的文件的路径。
            File file = new File(filePath);
            // 取得文件名。
            String filename = file.getName();

            // 以流的形式下载文件。
            fis = new BufferedInputStream(new FileInputStream(filePath));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            // 清空response
            response.reset();
            String userAgent = request.getHeader("User-Agent");

            if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
                filename = URLEncoder.encode(filename, "UTF-8");
            } else {
                // 非IE浏览器的处理:
                filename = new String(filename.getBytes("UTF-8"), "ISO-8859-1");
            }
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + filename);
            response.addHeader("Content-Length", "" + file.length());
            out = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            out.write(buffer);
        } catch (Exception e) {
            e.printStackTrace();
            response.setContentType("application/json;charset=utf-8");
            try {
                response.getWriter().write(JSON.toJSONString(DtoUtil.returnFail("出错啦", "E400")));
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        } finally {
            try {
                if (fis != null) {
                    fis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

    }

4.批量下载

public void downloadZip(String ids, HttpServletResponse response, HttpServletRequest request) {
        //响应头的设置
        response.reset();
        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        //设置压缩包的名字
        String billname = "附件包";
        String downloadName = billname + ".zip";
        //返回客户端浏览器的版本号、类型
        String agent = request.getHeader("USER-AGENT");
        //设置压缩流:直接写入response,实现边压缩边下载
        ZipOutputStream zipos = null;

        //循环将文件写入压缩流
        DataOutputStream os = null;

        try {
            //针对IE或者以IE为内核的浏览器:
            if (agent.contains("MSIE") || agent.contains("Trident")) {
                downloadName = java.net.URLEncoder.encode(downloadName, "UTF-8");
            } else {
                //非IE浏览器的处理:
                downloadName = new String(downloadName.getBytes("UTF-8"), "ISO-8859-1");
            }
            response.setHeader("Content-Disposition", "attachment;fileName=" + downloadName);
            zipos = new ZipOutputStream(new BufferedOutputStream(response.getOutputStream()));
            zipos.setMethod(ZipOutputStream.DEFLATED); //设置压缩方法


            List<String> fileIds = Arrays.asList(ids.split(","));
            String lastFileName=""; //记录上个文件名
            List<String> lastFileNames=new ArrayList<>();
            int number=0;  //上个文件名括号里的数字
            for (String fileId : fileIds) {
                //获取文件路径以及文件名
                ProjectFileEntity entity = projectFileDao.getFilePath(fileId);
                String filePath = entity.getFilePath();
                String fileName = entity.getFileName().substring(0,entity.getFileName().lastIndexOf("."));
                String suffix = entity.getFileName().substring( entity.getFileName().lastIndexOf(".") + 1);
                if (lastFileNames.contains(fileName)){
                    number++;
                    fileName=fileName+"("+number+")";
                }
                lastFileNames.add(fileName);
                File file = new File(filePath);
                    //添加ZipEntry,并ZipEntry中写入文件流
                    zipos.putNextEntry(new ZipEntry(fileName+"."+suffix));
                    os = new DataOutputStream(zipos);
                    InputStream is = new FileInputStream(file);
                    byte[] b = new byte[100];
                    int length = 0;
                    while ((length = is.read(b)) != -1) {
                        os.write(b, 0, length);
                    }
                    is.close();
                    zipos.closeEntry();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //关闭流
        try {
            os.flush();
            os.close();
            zipos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

5.在线打开文件 

Tips:下载的是本地文件,后续用了文件存储服务器后可能会改,还有个小问题,在线预览时    响应头    Content-Disposition   文件名称中文乱码 

 public void openFile(String filePath, HttpServletResponse response, HttpServletRequest request) {
        File f = new File(filePath);
        String suffix = f.getName().substring(f.getName().lastIndexOf(".") + 1);
        BufferedInputStream br = null;
        OutputStream out = null;
        try {
            if (!f.exists()) {
                response.sendError(404, "File not found!");
                return;
            }
            br = new BufferedInputStream(new FileInputStream(f));
            byte[] buf = new byte[1024];
            int len = 0;

            response.reset(); // 非常重要

            URL u = new URL("file:///" + filePath);
            if (suffix.equalsIgnoreCase("pdf")) {
                response.setContentType("application/pdf");
            } else {
                response.setContentType(u.openConnection().getContentType());
            }
            //解决文件名乱码
            String userAgent = request.getHeader("User-Agent");
            String formFileName;
            if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
                formFileName = URLEncoder.encode(f.getName(), "UTF-8");
            } else {
                // 非IE浏览器的处理:
                formFileName = new String(f.getName().getBytes("UTF-8"), "ISO-8859-1");
            }
            response.setHeader("Content-Disposition", "inline; filename=" + formFileName);
            response.setCharacterEncoding("UTF-8");

            out = response.getOutputStream();
            while ((len = br.read(buf)) > 0)
                out.write(buf, 0, len);
        } catch (IOException e) {
            e.printStackTrace();
             response.setContentType("application/json;charset=utf-8");
            try {
                response.getWriter().write(JSON.toJSONString(DtoUtil.returnFail("出错啦", "E400")));
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        } finally {
            try {
                if (br != null) {
                    br.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

    }

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

W先生'

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值