创建文件、文件上传下载、发送邮件附件以及文件点击预览功能(超详细注解)

根据模板生成文件

 @Override
    public File exportStuFileExcelNew(Studengt student, Page<StuFile> page)throws Exception{
        //获取当前系统时间
        LocalDate today = LocalDate.now();
        //打印日志报告------->根据模板生成文件
        logger.info("=============>正在生成企业档案报告");
        //读取模板路径(E:\workspace\test\demo\target\classes\template\test.xls)
        //this.getClass().getResource是得到当前对象对应的类文件(*.class)所在的目录下的文件。
        String excelPath = this.getClass().getResource("/").getPath()+"template/test.xls";
        //创建工作簿对象
        Workbook workbook = null;
        try {
        //把设定好的路径下的.xls的数据表读到workbook里
            workbook = new HSSFWorkbook(new FileInputStream(new File(excelPath)));
        }catch (Exception ex){
            logger.info("============>.xls文件创建出错",ex);
        }
        //设置单元格样式
        CellStyle style = workbook.createCellStyle();
        //单元格居中
        style.setAlignment(CellStyle.ALIGN_CENTER);
        //获取当前工作表序号
        Sheet sheet = workbook.getSheetAt(0);
        //设置行、单元格
        Row row = null;
        Cell cell = null;

        //根据条件查询,获取结果
        //传入参数为相关对象和导出的工作表页数
        Map<String, Object> map = this.findByInformation(student, page);
        Page<StuFile> page1 = (Page<StuFile>) map.get("page");
        List<StuFile> studentList = page1.getResults();

        //判断查询结果是否为空
        if(CollectionUtils.isNotEmpty(studentList)){
            //遍历查询出来的数据条数
            for (int i = 0,length = studentList.size(); i < length; i++) {
                //获取某学生的各种信息
                StuFile stu = studentList.get(i);

                StuFileOverView overView = new StuFileOverView();
                //设置学生唯一标识ID
                overView.setEid(stu.getEid());
                //由唯一标识去查询其他表中关联的学生信息
                StuFileOverView stuFileOverView = stuFileOverViewService.getByEid(overView);
                //作为判断条件,查询所得结果是否为空
                boolean flag = entFileOverView == null ? false : true;

                //行数加1,因为已经存在作为注解的第一行了
                row = sheet.createRow(i+1);

                //创建新的单元格,插入学生姓名信息
                Cell cell0 = row.createCell(0);
                //判断查询出来的结果是否为空,不为空则插入单元格
                if(StringUtils.isNotBlank(stu.getStuName())){
                    cell0.setCellValue(stu.getStuName());
                }

                //创建下一个新的单元格,插入学生学号
                Cell cell1 = row.createCell(1);
                //判断查询出来的结果是否为空,不为空则插入单元格
                if(StringUtils.isNotBlank(ent.getStuCode())){
                    cell1.setCellValue(ent.getStuCode());
                }

            }
        }
        //读取properties文件中的配置信息,即插入所有数据之后形成excel文件后保存的路径
        String dirPath = ReadConfig.UPLOAD_PATH;
        //.xls文件的路径
        String filePath = dirPath +"学生数据信息"+".xls";

        //先用File类打开本地文件,实例化输出流,然后调用流的读写方法写入数据,最后关闭流
        File file1 = new File(filePath);

        //应用输出流FileOutputStream把数据写入本地文件
        FileOutputStream fout = FileUtils.openOutputStream(file1);
       
        //用workbook对象是因为之前把---模板.xls---的数据表读到workbook里面了
        workbook.write(fout);
        fout.close();
        return file1;

    }

此段仅仅介绍由模板创建新的文件并写入相关查询所得数据,其中用到的有关查询方法的代码细则就不贴了。

文件上传

  /**
     * 文件上传
     * @param file  要上传的文件
     * @return
     * @throws Exception
     */
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
@ResponseBody
    public WebResponse upload(@RequestParam("file")MultipartFile file) throws Exception{
        FileUpload fileUpload = new FileUpload();
        //获取当前登陆的操作员真实姓名
        SysUser user = (SysUser)SecurityUtils.getSubject().getSession().getAttribute("user");
        String userName = user.getRealName();
      
        try {
            logger.info("上传的文件名为"+file.getOriginalFilename());
            //String fileName =   file.getOriginalFilename() + "-" + UUID.randomUUID().toString().replace("-", "");
            String fileName = file.getOriginalFilename().trim();
            //File fileLocal = new File(WebConfig.UPLOAD_PATH + fileName);
            //根据上传的文件路径和文件名创建该文件对象
            File fileLocal = new File(WebConfig.UPLOAD_PATH , fileName);
            //拷贝要上传的文件的一个字节流到服务器上保存上传文件的文件中,如果这个服务器上的文件文件不存在则新创建一个,存在的话将被重写进内容
            FileUtils.copyInputStreamToFile(file.getInputStream(), fileLocal);

            //保存上传文件的相关信息
            fileUpload.setFileName(fileName);
            fileUpload.setCreateTime(new Date());
            fileUpload.setUser(userName);
            fileUpload.setFilePath(fileLocal.getPath());
            fileUploadService.addFileRecord(fileUpload);
            return WebResponse.resSuccess("文件上传成功",fileLocal.getName());
        }catch (Exception e) {
            logger.error("上传失败", e);
            return WebResponse.resFail("文件上传失败",null);
        }
    }

文件下载  【记得要把流关闭了】

 /**
     * 文件在浏览器上下载
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "downloadFile" )
    @ResponseBody
    public void downloadFile(String fileName,HttpServletResponse response)throws Exception {
  try{
      
        //根据文件保存的路径和文件名创建该文件对象
        File file = new File(WebConfig.UPLOAD_PATH + fileName);
        //将该文件转换成文件输入流
        FileInputStream stream = new FileInputStream(file);
        //设置格式,防止乱码
        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        //response.setContentType("application/vnd.ms-excel");
        //防止文件名称乱码
        String name = new String(file.getName().getBytes("gb2312"), "ISO8859-1");
        response.setHeader("Content-Disposition", "attachment; fileName=" + name);
        //创建输出流对象,并把上面的属性塞入该对象中
        OutputStream os = response.getOutputStream();
        byte[] b = new byte[2048];
        int length;
        while ((length = stream.read(b)) > 0){
            //开始读写
            os.write(b,0,length);
        }
os.flush();
}catch(Exception e) {
            logger.error("下载失败:", e);
        }finally {
            try {
                if (stream !=null) {
                    stream.close();
                }
                if (os != null){
                    os.close();
                }
            } catch (IOException e) {
                logger.error("流关闭失败");
            }
        }

    }

文件下载二

        //导出文件名
        String fileName = "浙江省企业运行监测和风险防控系统" + today + ".xls";

        //创建表单
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet(sheetName);
    
             //待导出记录值
            List<MuEntData> findEntList = muEntDataDao.findEntList(key, dataBaseCriteria);

            //创建第一行表头内容
            sheet.createRow(0).createCell(0).setCellValue("企业名称");
            sheet.getRow(0).createCell(1).setCellValue("地方上报实际用地面积(亩)");
            sheet.getRow(0).createCell(2).setCellValue("税收实际贡献(万元)");
            sheet.getRow(0).createCell(3).setCellValue("工业增加值(万元)");
            sheet.getRow(0).createCell(4).setCellValue("综合能耗(吨标煤)");
            sheet.getRow(0).createCell(5).setCellValue("排污量(吨)");
            sheet.getRow(0).createCell(6).setCellValue("研发经费支出(万元)");
            sheet.getRow(0).createCell(7).setCellValue("主营业务收入(万元)");
            sheet.getRow(0).createCell(8).setCellValue("年平均职工人数(人)");
            for (int i = 1; i < 1 + findEntList.size(); i++) {
                HSSFRow hssfRow1 = sheet.createRow(i);
                MuEntData muEntData = findEntList.get(i - 1);
                //从第二行开始插入值
                hssfRow1.createCell(0).setCellValue(muEntData.getEntName()!=null?muEntData.getEntName():"");
                hssfRow1.createCell(1).setCellValue(muEntData.getLandArea()!=null?muEntData.getLandArea().toString():"");
                hssfRow1.createCell(2).setCellValue(muEntData.getTaxRevenue()!=null?muEntData.getTaxRevenue().toString():"");
                hssfRow1.createCell(3).setCellValue(muEntData.getIndustAddValue()!=null?muEntData.getIndustAddValue().toString():"");
                hssfRow1.createCell(4).setCellValue(muEntData.getAllEnergyConsume()!=null?muEntData.getAllEnergyConsume().toString():"");
                hssfRow1.createCell(5).setCellValue(muEntData.getPollutionRight()!=null?muEntData.getPollutionRight().toString():"");
                hssfRow1.createCell(6).setCellValue(muEntData.getResearchMoney()!=null?muEntData.getResearchMoney().toString():"");
                hssfRow1.createCell(7).setCellValue(muEntData.getMainBusinessIncome()!=null?muEntData.getMainBusinessIncome().toString():"");
                hssfRow1.createCell(8).setCellValue(muEntData.getYearAverageWorkers()!=null?muEntData.getYearAverageWorkers().toString():"");
            

        //数据写入
        try {
            fileName = URLEncoder.encode(sheetName +"-"+ fileName, "UTF-8").replace("+", "%20");
            ByteArrayOutputStream osOut = new ByteArrayOutputStream();
            wb.write(osOut);
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment; fileName=" + fileName);

            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            toClient.write(osOut.toByteArray());
            toClient.flush();
            toClient.close();


        } catch (Exception e) {
            logger.error(fileName + "下载失败", e);
        }

文件数据导出

 public void systemLogDownload(HttpServletResponse response, SystemLogCriteria systemLogCriteria) {
        try {
            Integer platformId = (Integer) SecurityUtils.getSubject().getSession().getAttribute("platformId");
            List<SystemLog> list = systemLogService.getDownloadList(systemLogCriteria,platformId);
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            HSSFWorkbook wb = new HSSFWorkbook();
            HSSFSheet sheet = wb.createSheet("系统日志");
            sheet.createRow(0).createCell(0).setCellValue("序号");
            sheet.getRow(0).createCell(1).setCellValue("用户名");
            sheet.getRow(0).createCell(2).setCellValue("姓名");
            sheet.getRow(0).createCell(3).setCellValue("操作类型");
            sheet.getRow(0).createCell(4).setCellValue("操作模块");
            sheet.getRow(0).createCell(5).setCellValue("操作时间");
            for (int i = 1; i < 1 + list.size(); i++) {
                HSSFRow hssfRow1 = sheet.createRow(i);
                SystemLog systemLog = list.get(i - 1);
                hssfRow1.createCell(0).setCellValue(i);
                hssfRow1.createCell(1).setCellValue(systemLog.getUserName());
                hssfRow1.createCell(2).setCellValue(systemLog.getRealName());
                hssfRow1.createCell(3).setCellValue(systemLog.getOperate());
                hssfRow1.createCell(4).setCellValue(systemLog.getModuleName());
                hssfRow1.createCell(5).setCellValue(formatter.format(systemLog.getTime()));
            }
            String fileName = URLEncoder.encode("系统日志.xls", "UTF-8").replace("+", "%20");
            ByteArrayOutputStream osOut = new ByteArrayOutputStream();
            wb.write(osOut);
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment; fileName=" + fileName);

            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            toClient.write(osOut.toByteArray());
            toClient.flush();
            toClient.close();
        }catch (Exception e){
            logger.error("系统配置---日志管理---日志下载失败",e);
        }
    }

下载excel模板

    /**
     * 下载上传模板
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "downloadFile" )
    @ResponseBody
    public void downloadFile(HttpServletRequest request, HttpServletResponse response) throws Exception {
        try {
            String filePath = this.getClass().getResource("/").getPath() + "template/uploadTemplate.xlsx";
            String fileName = "数据上传模板.xlsx";
            logger.info("读取excle模板路径...");
            //获得浏览器请求头中的User-Agent
            String agent = request.getHeader("User-Agent");
            //在浏览器头信息中 寻找相应的字符串,返回它最开始出现的位置。
            //当找到字符串时,返回值范围是[0,agent.length-1]这个区间,没找到就返回-1,所以当返回值大于-1时,就说明找到了相应字符串。
            boolean isMSIE = (agent != null && (agent.indexOf("Trident") != -1 || agent.indexOf("MSIE") != -1));
            if (!isMSIE) {
                if (agent.indexOf("Edge") != -1) {
                    filePath = new String(filePath.getBytes(), "UTF-8");
                    fileName = new String(fileName.getBytes("gb2312"), "ISO8859-1");
                } else {
                    filePath = new String(filePath.getBytes(), "UTF-8");
                    fileName = new String(fileName.getBytes("utf-8"), "iso-8859-1");
                }

            } else {
                filePath = new String(filePath.getBytes(), "UTF-8");
                fileName = URLEncoder.encode(fileName, "UTF-8").replace("+", "%20");
            }

            InputStream stream = new FileInputStream(filePath);
            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition", "attachment; fileName=" + fileName);
            OutputStream os = response.getOutputStream();
            byte[] b = new byte[2048];
            int length;
            while ((length = stream.read(b)) > 0) {
                os.write(b, 0, length);

            }

            logger.info("excle模板下载成功");
            // 这里主要关闭。
            os.close();
            stream.close();

        } catch (Exception e) {
            logger.info("下载模板出错", e);
        }
    }

根据ftl模板发送邮件及邮件附件

/**
     * 根据ftl模板发送邮件
     *
     * @param toEmail   收件人邮箱地址,多个地址用英文逗号(,)隔开
     * @param sendEmailType 邮件类型
     * @param path      附件路径
     */

    public void sendEmailWithAttachment(Map<String, Object> map,String toEmail, SendEmailType sendEmailType, String path) {
       

        //创建一个线程,完成异步调用
        Thread th = new Thread(() -> {
            //新建一个MimeMessage对象,该类是个能理解MIME类型和头的电子邮件消息
            MimeMessage msg;
            try {
                //MimeMessages为复杂邮件模板,支持文本、附件、html、图片等。
                msg = mailSender.createMimeMessage();
                //创建MimeMessageHelper对象,处理MimeMessage的辅助类
                //true表示是否为multiparty邮件,ENCODING表示MimeMessage的编码内容的字符集
                MimeMessageHelper helper = new MimeMessageHelper(msg, true, ENCODING);
                
                //使用辅助类MimeMessage设定参数:发件人邮箱
                helper.setFrom(Config.FROM_EMAIL);
                //收件人邮箱地址,多个地址用英文逗号(,)隔开
                String[] toEmails = toEmail.split(",");
                //设置收件人地址
                helper.setTo(toEmails);

                //设置邮件标题,sendEmailType.getSubject()获取邮件标题类型
                //ENCODING表示编码内容的字符集
                //"B"表示为目标编码格式,Base64的编码方式(加密)
                helper.setSubject(MimeUtility.encodeText(sendEmailType.getSubject(), ENCODING, "B"));

                //sendEmailType.getModelName()获取邮件模板的名称
                // true表示text的内容为html
                helper.setText(getMailText(map,sendEmailType.getModelName()), true);

                // 这里的方法调用和插入图片是不同的,解决附件名称的中文问题
                File file = new File(path);
                //给附件重命名,不会影响本地下载好的文件的名称
                File newNameFile =new File("企业数据信息.xls");
                //添加附件文件,newNameFile.getName()新的文件名称,file为传入参数path路径下的文件
                helper.addAttachment(MimeUtility.encodeWord(newNameFile.getName()), file);

                //发送邮件
                mailSender.send(msg);
                logger.info("邮件发送成功,主题为:" + sendEmailType.getSubject() + " >>> 邮件模板为:" + sendEmailType.getModelName() + ";参数为:" + JsonUtil.toJsonString(map));

            } catch (Exception e) {

                logger.error("邮件发送失败,主题为:" + sendEmailType.getSubject() + " >>> 邮件模板为:" + sendEmailType.getModelName() + ";参数为:" + JsonUtil.toJsonString(map) + ";" + e);

            }

        });
        th.start();
    }

    /**
     * 构造邮件,map中的参数将替换ftl对应参数的值
     *
     * @return modelName    邮件模板名称(包括后缀)
     * @throws Exception 异常抛出
     */
    private String getMailText(Map<String, Object> map, String modelName) throws Exception {
        // 通过指定模板名获取FreeMarker模板实例
        Template template = freeMarkerConfigurer.getConfiguration().getTemplate(modelName);
        // 解析模板并替换动态数据,最终content将替换模板文件中的${content}标签。
        return FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
    }

    //下面这两个方法要在spring中配置
    public void setMailSender(JavaMailSender mailSender) {
        this.mailSender = mailSender;
    }

    public void setFreeMarkerConfigurer(FreeMarkerConfigurer freeMarkerConfigurer) {
        this.freeMarkerConfigurer = freeMarkerConfigurer;
    }
}

有关spring-email.xml的配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="freeMarkerConfigurer"
          class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
        <property name="templateLoaderPath" value="classpath:template" /> <!-- 指定模板文件目录 -->
        <property name="freemarkerSettings"><!-- 设置FreeMarker环境属性 -->
            <props>
                <prop key="template_update_delay">1800</prop> <!--刷新模板的周期,单位为秒 -->
                <prop key="default_encoding">UTF-8</prop> <!--模板的编码格式 -->
                <prop key="locale">zh_CN</prop> <!--本地化设置 -->
            </props>
        </property>

        <property name="freemarkerVariables">
            <map>
                <entry key="webRoot" value="${webRoot}"></entry><!-- 模板中图片访问路径,一般是http://localhost:8080 -->
            </map>
        </property>
    </bean>
    <!-- 注意:这里的参数(如用户名、密码)都是针对邮件发送者的 -->
    <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
        <property name="host" value="${regist.email.host}"/> <!-- 服务器 -->
        <property name="port" value="${regist.email.port}"/> <!-- 一般情况下都为25 -->
        <property name="protocol" value="smtp"/>
        <property name="username" value="${regist.email.username}"/> <!-- 发送者用户名 -->
        <property name="password" value="${regist.email.password}"/><!-- 发送者密码 -->
        <property name="defaultEncoding" value="UTF-8"/>
        <property name="javaMailProperties">
            <props>
                <prop key="mail.smtp.auth">true</prop>
                <prop key="mail.smtp.timeout">1800</prop>
            </props>
        </property>
    </bean>

    <bean id="emailService" class="com.test.demo.service.SendEmailService">
        <property name="mailSender" ref="mailSender"></property>
        <property name="freeMarkerConfigurer" ref="freeMarkerConfigurer"></property>
    </bean>


</beans>

邮件模板:先创建html格式文件,然后重命名为 .ftl 后缀名

模板中插入的图片放在项目里,然后通过url去访问,不然在邮件中是看不到图片的。当然也可以放在服务器里,就需要另一种方式了。

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <style type="text/css">
        body {
            color: #333;
        }
        p a {
            text-decoration:none;
        }
        .content2 {
            margin-left: 20px;
            margin-bottom: 20px;
            margin-top: 180px;

        }
      
        .text-indent-2em {
            text-indent: 2em;
        }
    </style>
</head>

<body>
<div style="width: 800px; height: 350px; margin-left: auto; margin-right: auto; border: 1px solid #e5e5e5;">
    <div style="width: 100%; height: 110px;">
        <table style="width: 100%;">
            <tr>
                <img alt="发送邮件" style="width: 800px; "src="${webRoot}/dist/images/email.png"/>
            </tr>
        </table>
    </div>
    <div style="margin: 0 0px 0 0px;">
        <p class="content2" style="margin-top: 60px;font-size: 25PX; margin-left: 120px;">您好,附件请注意查收。 </p> 
    </div>
</div>
</body>
</html>

发送邮件

	/**
	 * 学生档案列表导出
	 * @param student
	 * @param page
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "exportStuFileExcelNew",method = RequestMethod.GET)
	@ResponseBody
	public ResponseWrapper exportStuFileExcelNew(Student student, Page<EntFile> page, HttpServletResponse response){
        //创建邮件发送的对象
		EmailSendInformation emailSendInformation = new EmailSendInformation();


/*
原功能为文件由浏览器下载,现在改为邮箱直接发送文件


		//设置导出的数量,即excel中sheet的页面数
		page.setPageNum(1);
		//设置excel文件数据导出数量上限
		page.setPageSize(Integer.parseInt(WebConfig.STUFILE_EXPORT_NUM));
        //map中放入参数
		Map<String, Object> map = new HashMap<>();
		map.put("exportDate","发送附件");
		try {
            //把信息插入文件模板,生成新的文件
            //这里调用了开头的方法
			File file = stuFileService.exportStuFileExcelNew(student, page);
            //输入流
			FileInputStream stream = new FileInputStream(file);
			response.setCharacterEncoding("utf-8");
            //使用Content-Type来表示具体请求中的媒体类型信息。
			response.setContentType("multipart/form-data");
			//response.setContentType("application/vnd.ms-excel");

			String fileName = new String(file.getName().getBytes("gb2312"), "ISO8859-1");
			response.setHeader("Content-Disposition", "attachment; fileName=" + fileName);
            //输出流,
			OutputStream os = response.getOutputStream();
            //2048是保证数组的容量
			byte[] b = new byte[2048];
			int length;
            
            //接受屏幕输入,存入b数组,同时将读取的个数赋值给length
            //stream.read()从输入流中都去一定数量的字节,并将其存储在缓冲区数组b中
            //以整数形式返回实际读取的字节数
			while ((length = stream.read(b)) > 0){
                //参数b,源缓冲区被写入到流
                //参数0,开始在数据偏移,指b数据中偏移量
                //参数length,字节写数
                //write方法会一次从b数组中写入length个长度的b[i]值
				os.write(b,0,length);
			}
*/
            //获取相对路径下的文件作为邮件附件发送
			emailService.sendEmailWithAttachment(map,"此处填写收件人邮箱地址", SendEmailType.EXPORT_DATA,file.getPath());
			logger.info("=============>学生档案导出成功");
			return ResponseWrapper.markSuccess("导出成功");
		}catch (Exception ex){
			logger.info("=============>学生档案导出失败",ex);
			return ResponseWrapper.markError("导出失败");
		}
	}

其中提到的数据偏移是指,像"abcdefg"这一字符串,index标好序列的话,依次是0、1、2、3、4、5、6,那么数据偏移数字为3的话,就是从字符"d"开始读取;偏移数字为0的话,就是从字符"a"开始读取;

文件上传到阿里云

public WebResponse upload(@RequestParam("file")MultipartFile file) throws Exception{
    String uuid = UUidUtil.get32Uuid();
    //获取要上传的文件(上传路径+文件名)
    File fileLocal = new File(WebConfig.UPLOAD_PATH, uuid + "-" + file.getOriginalFilename());
    //将建好的文件用流的形式读写进去(顺序不能反了,反了url就为空了)
    FileUtils.copyInputStreamToFile(file.getInputStream(), fileLocal);
    //上传到服务器
    String ossUrl = ossService.uploadFile(fileLocal);
    logger.info("上传的URL为" +ossUrl);
    String fileName= file.getOriginalFilename().trim();
    logger.info("上传的文件名为" + file.getName());
    //然后把一些相关信息存到表里就OK了
        return WebResponse.resSuccess("上传成功", "");
    }

oss的配置信息,本地的一些配置信息就不贴了。

文件从阿里云上下载

这一块做的是从阿里云上下载目标文件存到目标盘里面,然后提供给用户下载的功能。但是用户下载完之后,需要把目标文件删除,不然用户下载一次,就会存一次。

然后在调用file.delete()功能的时候,发现该目标文件一直不能被删除,就算关闭了文件流,还是无法删除。最后使用的方法使用以下的方法,然后测试发下,删除是可以了的。

经过这次的文件下载以及删除,体会到了,从阿里客户端下载的文件和从用户角度下载的文件其实是两份不同的文件。之前一直以为从阿里下载的文件的过程就是用户下载到自己本地的文件过程,其实不然。阿里下载,配置的目标路径,那么它下载好的文件会存放在目标路径里面,然后用户下载的存放路径会根据他自身配置的下载路径进行文件存放。从阿里下载文件只是根据提供的文件路径进行用户端流式的文件下载。

try{ 

 }finally{ 

  }
 //通过文件展示名称找到要下载文件的相关信息
    ShareFile sharefile = shareFileService.findFileInfo(fileName);

//从oss读取文件
    String ossUrl = sharefile.getFilePath();
    String fileTitle = ossUrl.substring(ossUrl.lastIndexOf("-")+ 1,ossUrl.length());
    OSSClient ossClient = new OSSClient(WebConfig.END_POINT, WebConfig.ACCESS_KEY_ID, WebConfig.ACCESS_KEY_SECRET);
    // 下载OSS文件到本地文件。如果指定的本地文件存在会覆盖,不存在则新建。
    ossClient.getObject(new GetObjectRequest(WebConfig.BUCKET_NAME_OSS, ossUrl), new File(WebConfig.UPLOAD_PATH+fileTitle));

    //文件临时下载到服务器上
    File file = new File(WebConfig.UPLOAD_PATH + fileTitle);
    FileInputStream stream = new FileInputStream(file);
    response.setCharacterEncoding("utf-8");
    response.setContentType("multipart/form-data");
    //response.setContentType("application/vnd.ms-excel");
    String name = new String(file.getName().getBytes("gb2312"), "ISO8859-1");
    response.setHeader("Content-Disposition", "attachment; fileName=" + name);
    OutputStream os = response.getOutputStream();
    byte[] b = new byte[2048];
    int length;
    while ((length = stream.read(b)) > 0){
        os.write(b,0,length);
    }

    // 关闭OSSClient。
    ossClient.shutdown();

    //删除服务器中的临时文件
    file.delete();

根据文件后缀名判断文件格式(word\excel\pdf)

String[] strArray = fileName.split("\\.");
int suffixIndex = strArray.length -1;
logger.info("上传文件的后缀名为"+strArray[suffixIndex]);
FileShareUploadHistory fileShareUploadHistory = new FileShareUploadHistory();
if(strArray[suffixIndex].equals("docx")|| strArray[suffixIndex].equals("doc")){
    fileShareUploadHistory.setFileFormat("word");
}
else if(strArray[suffixIndex].equals("xlsx") || strArray[suffixIndex].equals("xls")){
    fileShareUploadHistory.setFileFormat("excel");
}
else if(strArray[suffixIndex].equals("pdf")){
    fileShareUploadHistory.setFileFormat("pdf");
}

文件在线预览----上(主要代码)

   /**
     * 预览
     * @param fileName
     */
@RequestMapping(value = "previewOnHtml" , method = RequestMethod.GET)
@ResponseBody
    public void getPdf(@RequestParam(value = "fileName") String fileName, HttpServletResponse response) {

        logger.info("预览的文件名为"+fileName);
        //TRANSFORM_HTML_RESULT_PATH 为 openoffice转换html的磁盘路径
        String outpath = WebConfig.TRANSFORM_HTML_RESULT_PATH;
        //UPLOAD_PATH 为 要做预览的文件的保存路径
        File file = new File(WebConfig.UPLOAD_PATH,fileName);
        if(!file.exists()){
            logger.info("file不存在"+file.getName());
        }
        //获取文件后缀名
        String ass = fileName.substring(fileName.lastIndexOf(".")+1,fileName.length());
        //获取文件头
        String head = fileName.substring(0,fileName.lastIndexOf("."));
        //拼接成XXX.html格式的文件名
        File outputFile = new File(outpath,head+".html");
        if(!outputFile.exists()){
            logger.info("文件不存在,开始转换");
            try {
            //工具类,其中OPEN_OFFICE_HOST和OPEN_OFFICE_PORT 为 openoffice远程地址和端口
            Office2PDFUtil dp = new Office2PDFUtil(WebConfig.OPEN_OFFICE_HOST,WebConfig.OPEN_OFFICE_PORT,
                    file, outputFile, ass, "html");
            //开启线程
            dp.start();
            //调用线程等待该线程完成后,才能继续用下运行
            dp.join();
            }catch (Exception e){
                logger.error("预览失败_",e);
                return;
            }
        }
        try {
            response.reset();
            response.setHeader("Content-type", "text/html;charset=utf-8");
            //获取了一个输出流 输出的对象是页面
            PrintWriter printWriter = response.getWriter();
            //设置好文件格式,防止出现乱码
            String s = FileUtils.readFileToString(outputFile,"utf-8");
            s = s.replace("<TD","<TD style=\"border: 1px solid #c0c0c0;\"");
            s = s.replace("<TABLE","<TABLE style=\"white-space: nowrap\"");
            printWriter.write(s);
            printWriter.close();
        }catch (Exception e) {
            logger.error("预览失败",e);
        }

    }

文件在线预览----下(工具类)

import com.artofsolving.jodconverter.DefaultDocumentFormatRegistry;
import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.DocumentFormat;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.StreamOpenOfficeDocumentConverter;
import java.io.File;
import java.net.ConnectException;

public class Office2PDFUtil extends Thread  {
    private String host;
    private String port;
    private File inputFile;// 需要转换的文件
    private File outputFile;// 输出的文件
    private String docFormat;//需要转换的文件格式
    private String outFormat;//输出的文件的文件格式

    public String getOutFormat() {
        return outFormat;
    }
    public void setOutFormat(String outFormat) {
        this.outFormat = outFormat;
    }
    public String getDocFormat() {
        return docFormat;
    }
    public void setDocFormat(String docFormat) {
        this.docFormat = docFormat;
    }


    public Office2PDFUtil(String host , String port,File inputFile, File outputFile, String docFormat, String outFormat) {
        this.host = host;
        this.port = port;
        this.inputFile = inputFile;
        this.outputFile = outputFile;
        this.docFormat=docFormat;
        this.outFormat=outFormat;

    }

    public void docToPdf() {
        OpenOfficeConnection connection = new SocketOpenOfficeConnection(host, Integer.parseInt(port));

        try {

            // 获得文件格式
            DefaultDocumentFormatRegistry formatReg = new DefaultDocumentFormatRegistry();
            DocumentFormat pdfFormat = formatReg.getFormatByFileExtension(this.outFormat);
            DocumentFormat docFormat = formatReg.getFormatByFileExtension(this.docFormat);
            connection.connect();
            DocumentConverter converter = new StreamOpenOfficeDocumentConverter(connection);
//                DocumentConverter converter = new Office2PDFConver(connection);

            converter.convert(this.getInputFile(), docFormat, this.getOutputFile(), pdfFormat);
//                converter.convert(this.getInputFile(), this.getOutputFile());
        } catch (ConnectException cex) {
            cex.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
                connection = null;
            }
//                this.destroy();
        }
    }

    /**
     * 由于服务是线程不安全的,所以……需要启动线程
     */
    @Override
    public void run() {
        this.docToPdf();
    }
    public File getInputFile() {
        return inputFile;
    }
    public void setInputFile(File inputFile) {
        this.inputFile = inputFile;
    }
    public File getOutputFile() {
        return outputFile;
    }
    public void setOutputFile(File outputFile) {
        this.outputFile = outputFile;
    }

}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值