根据模板生成文件

 @Overridepublic 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();//设置学生唯一标识IDoverView.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)
@ResponseBodypublic 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" )@ResponseBodypublic 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" )@ResponseBodypublic 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-AgentString 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的内容为htmlhelper.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/beanshttp://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)@ResponseBodypublic 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)
@ResponseBodypublic 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();}}/*** 由于服务是线程不安全的,所以……需要启动线程*/@Overridepublic 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;}}

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

  1. c#ftp操作全解:创建删除目录,上传下载文件,删除移动文件,文件改名,文件目录查询

    全栈工程师开发手册 (作者:栾鹏) c#教程全解 c#实现ftp的操作.包括创建删除目录,上传下载文件,删除移动文件,文件改名,文件目录查询. 在调试ftp前,需要在目标主机上开启ftp功能.这里在本 ...

  2. javaWeb - 文件的上传下载

    文件的上传和下载 <%--文件的上传和下载文件的上传和下载,是非常常见的功能.很多的系统中,或者软件中都经常使用文件的上传和下载.比如:QQ 头像,就使用了上传.邮箱中也有附件的上传和下载功能. ...

  3. Java使用SFTP和FTP两种连接服务器的方式实现对文件的上传下载

    一.Java实现对SFTP服务器的文件的上传下载: 1.添加maven依赖: <dependency><groupId>com.jcraft</groupId>&l ...

  4. SmartUpload上传下载及文件名和文件内容中文问题

    一.安装篇 jspSmartUpload是由www.jspsmart.com网站开发的一个可免费使用的全功能的文件上传下载组件,适于嵌入执行上传下载操作的JSP文件中.该组件有以下几个特点: 1.使用 ...

  5. 文件的上传下载功能的实现(包括进度条)[telerik控件]

    文件的上传下载功能的实现(包括进度条) 1.准备工作 首先我们需要Telerik控件,数据库,上传文件文件夹. Telerik控件: RadUpload.RadProgressManager.RadP ...

  6. ACTIVEX实现大文件FTP上传下载---上

    ACTIVEX实现大文件FTP上传 在Windows 操作系统下,有一个重要的机制,就是OLE ,就是可以让某个应用程序(OLE Controller)访问其它应用程序(OLE Server)所提供的 ...

  7. Linux环境Shell脚本上传下载阿里云OSS文件

    为什么80%的码农都做不了架构师?>>>    Linux环境Shell脚本上传下载阿里云OSS文件 背景 工作中由于我们项目生成的日志文件比较重要,而本地磁盘空间有限存储不了多久, ...

  8. java 文件下载 组件_java文件夹上传下载组件

    核心原理: 该项目核心就是文件分块上传.前后端要高度配合,需要双方约定好一些数据,才能完成大文件分块,我们在项目中要重点解决的以下问题. *如何分片: *如何合成一个文件: *中断了从哪个分片开始. ...

  9. ssm框架验证码图片加载不出_基于SSM框架的文件图片上传/下载功能实现

    前一段时间很多做毕业设计的同学问:如何写图片和文件的上传下载功能,今天正好有时间,所以就做了一个案例,详细的讲解这个功能. 框架结构: 对于很多做过开发的而言,上传功能肯定都用过,而且用到的场景很多, ...

  10. 基于layui.upload.js 拖拽文件/文件夹上传下载

    layui.upload.js 拖拽文件/文件夹上传下载 前言 js代码 页面使用(我这里用的是uploader.jsp) CSS文件 上传效果 总结 前言 项目需求完成文件上传,可以拖拽上传文件/文 ...

最新文章

  1. c/c++ 修改文件的创建时间,修改时间,访问时间 [和弦]
  2. mysql数据库连接配置路径_[zz]MySQL数据库主从同步安装与配置总结
  3. SpringMVC传递JSON数据的方法
  4. vmtouch--the Virtual Memory Toucher
  5. hadoop学习6 运行map reduce出错
  6. nginx的模块化体系结构
  7. leetcode 240. 搜索二维矩阵 II
  8. ref改变样式 vue_我用React和Vue构建了同款应用,对比看看(2020版)
  9. sklearn机器学习之特征工程
  10. 筛数方法相关系数_相关系数的检验方法.ppt
  11. Akash,全球首个去中心化云计算
  12. Python合并两个有序链表
  13. java多线程 Semaphore CountDownLatch ScheduledExecutorService
  14. OSChina 周三乱弹 ——你是有多寂寞啊,看光头强都……
  15. python汉字字体宋体_设置matplotlib中文显示(宋体)
  16. 所有的I/O端口都是兼容CMOS和TTL 表示什么意思
  17. Spring securty<三> 认证案例代码
  18. 高效能人士七个习惯(三)
  19. Windows 使用技巧 -- 自定义桌面图标显示
  20. IE 10浏览器使用心得:界面简洁、功能很强大

热门文章

  1. mui 新闻资讯app模板下载_简单易学的app制作教程:6步0编程进行app开发
  2. 70个Python练手项目列表,得不到永远会骚动~
  3. Fanuc数控系统程序传输开发接口的系统结构、功能及相关技术
  4. 用kruskal算法求最小生成树各边的权值之和
  5. 畅游Google Android Developer
  6. 你不知道的服装ERP系统的功能模块与好处!
  7. 单片机怎么通过按键控制计时器的开始和停止_消毒柜、吸油烟机控制电路简介...
  8. COMPUTEX 2021 Virtual将于下周华丽登场!观展必看亮点抢先曝光
  9. PCA算法在人脸识别中的应用
  10. 让人兴奋的中国高速公路