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

本文主要是介绍创建文件、文件上传下载、发送邮件附件以及文件点击预览功能(超详细注解),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

根据模板生成文件

 @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;}}

 

这篇关于创建文件、文件上传下载、发送邮件附件以及文件点击预览功能(超详细注解)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/676130

相关文章

将Mybatis升级为Mybatis-Plus的详细过程

《将Mybatis升级为Mybatis-Plus的详细过程》本文详细介绍了在若依管理系统(v3.8.8)中将MyBatis升级为MyBatis-Plus的过程,旨在提升开发效率,通过本文,开发者可实现... 目录说明流程增加依赖修改配置文件注释掉MyBATisConfig里面的Bean代码生成使用IDEA生

Linux系统配置NAT网络模式的详细步骤(附图文)

《Linux系统配置NAT网络模式的详细步骤(附图文)》本文详细指导如何在VMware环境下配置NAT网络模式,包括设置主机和虚拟机的IP地址、网关,以及针对Linux和Windows系统的具体步骤,... 目录一、配置NAT网络模式二、设置虚拟机交换机网关2.1 打开虚拟机2.2 管理员授权2.3 设置子

Linux系统中卸载与安装JDK的详细教程

《Linux系统中卸载与安装JDK的详细教程》本文详细介绍了如何在Linux系统中通过Xshell和Xftp工具连接与传输文件,然后进行JDK的安装与卸载,安装步骤包括连接Linux、传输JDK安装包... 目录1、卸载1.1 linux删除自带的JDK1.2 Linux上卸载自己安装的JDK2、安装2.1

Java实现文件图片的预览和下载功能

《Java实现文件图片的预览和下载功能》这篇文章主要为大家详细介绍了如何使用Java实现文件图片的预览和下载功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... Java实现文件(图片)的预览和下载 @ApiOperation("访问文件") @GetMapping("

SpringCloud动态配置注解@RefreshScope与@Component的深度解析

《SpringCloud动态配置注解@RefreshScope与@Component的深度解析》在现代微服务架构中,动态配置管理是一个关键需求,本文将为大家介绍SpringCloud中相关的注解@Re... 目录引言1. @RefreshScope 的作用与原理1.1 什么是 @RefreshScope1.

SpringKafka消息发布之KafkaTemplate与事务支持功能

《SpringKafka消息发布之KafkaTemplate与事务支持功能》通过本文介绍的基本用法、序列化选项、事务支持、错误处理和性能优化技术,开发者可以构建高效可靠的Kafka消息发布系统,事务支... 目录引言一、KafkaTemplate基础二、消息序列化三、事务支持机制四、错误处理与重试五、性能优

SpringIntegration消息路由之Router的条件路由与过滤功能

《SpringIntegration消息路由之Router的条件路由与过滤功能》本文详细介绍了Router的基础概念、条件路由实现、基于消息头的路由、动态路由与路由表、消息过滤与选择性路由以及错误处理... 目录引言一、Router基础概念二、条件路由实现三、基于消息头的路由四、动态路由与路由表五、消息过滤

Java使用Curator进行ZooKeeper操作的详细教程

《Java使用Curator进行ZooKeeper操作的详细教程》ApacheCurator是一个基于ZooKeeper的Java客户端库,它极大地简化了使用ZooKeeper的开发工作,在分布式系统... 目录1、简述2、核心功能2.1 CuratorFramework2.2 Recipes3、示例实践3

Spring Boot 3.4.3 基于 Spring WebFlux 实现 SSE 功能(代码示例)

《SpringBoot3.4.3基于SpringWebFlux实现SSE功能(代码示例)》SpringBoot3.4.3结合SpringWebFlux实现SSE功能,为实时数据推送提供... 目录1. SSE 简介1.1 什么是 SSE?1.2 SSE 的优点1.3 适用场景2. Spring WebFlu

基于SpringBoot实现文件秒传功能

《基于SpringBoot实现文件秒传功能》在开发Web应用时,文件上传是一个常见需求,然而,当用户需要上传大文件或相同文件多次时,会造成带宽浪费和服务器存储冗余,此时可以使用文件秒传技术通过识别重复... 目录前言文件秒传原理代码实现1. 创建项目基础结构2. 创建上传存储代码3. 创建Result类4.