package com.xunmei.file.service; import cn.hutool.core.date.DateUtil; import cn.hutool.core.util.ObjectUtil; import com.lowagie.text.Document; import com.lowagie.text.Font; import com.lowagie.text.pdf.BaseFont; import com.lowagie.text.pdf.PdfPTable; import com.lowagie.text.pdf.PdfWriter; import com.xunmei.common.core.utils.uuid.UUID; import com.xunmei.file.utils.FileDownUtils; import com.xunmei.file.utils.FileUploadUtils; import com.xunmei.file.utils.PdfUtil; import com.xunmei.file.vo.ItextPdfTableVo; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Primary; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.net.URLDecoder; import java.nio.charset.StandardCharsets; import java.util.Date; import java.util.Map; /** * 本地文件存储 * * @author xunmei */ @Primary @Service public class LocalSysFileServiceImpl implements ISysFileService { private static final Logger log = LoggerFactory.getLogger(LocalSysFileServiceImpl.class); /** * 上传文件存储在本地的根路径 */ @Value("${file.path}") private String localFilePath; @Autowired private HttpServletRequest request; private static String getLocalFilePath(String prefix, String businessType, String fileName) { final String path = File.separator + businessType + File.separator + DateUtil.format(new Date(), "yyyy" + File.separator + "MM" + File.separator + "dd" + File.separator); File desc = new File(path + fileName); log.info("当前上传文件地址:{}", desc.getAbsolutePath()); if (!desc.exists()) { if (!desc.getParentFile().exists()) { log.info("创建文件夹:{}", desc.getParentFile()); desc.getParentFile().mkdirs(); } } return desc.getPath(); } /** * 本地文件上传接口 * * @param file 上传的文件 * @return 访问地址 * @throws Exception */ @Override public String uploadFile(MultipartFile file) throws Exception { String name = FileUploadUtils.upload(localFilePath, file); // String url = domain + localFilePrefix + name; return name; } @Override public String uploadFile(MultipartFile file, String busType) throws Exception { String name = FileUploadUtils.upload(localFilePath, file, busType); // String url = domain + localFilePrefix + name; return name; } @Override public void downloadFile(HttpServletResponse response, String filePath) { ByteArrayOutputStream out = null; try { filePath = localFilePath + filePath; filePath = URLDecoder.decode(filePath, "UTF-8"); out = FileDownUtils.downloadFile(filePath); String fileSuffix = FileDownUtils.getFileSuffix(filePath); String formFileName = UUID.randomUUID().toString() + fileSuffix; String userAgent = request.getHeader("User-Agent"); // 针对IE或者以IE为内核的浏览器: if (StringUtils.isNotEmpty(userAgent) && (userAgent.contains("MSIE") || userAgent.contains("Trident"))) { formFileName = java.net.URLEncoder.encode(formFileName, "UTF-8"); } else { // 非IE浏览器的处理: formFileName = new String(formFileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1); } response.reset(); response.setCharacterEncoding("UTF-8"); response.addHeader("Content-Disposition", "attachment;filename=" + formFileName); response.addHeader("Content-Length", "" + out.size()); out.writeTo(response.getOutputStream()); response.setContentType("application/octet-stream"); out.flush(); out.close(); } catch (IOException e) { log.error("文件下载失败! "); e.printStackTrace(); } finally { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } @Override public void getFileStream(String path, HttpServletResponse response) { if (ObjectUtil.isEmpty(path)) { return; } if (!path.startsWith(this.localFilePath)) { path = this.localFilePath + path; } try { File file = new File(path); FileInputStream inputStream = new FileInputStream(file); int i = path.lastIndexOf(File.separator); String fileName = path.substring(i + 1); // 设置响应头 response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName); response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE); // 将文件流写入响应输出流 byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { response.getOutputStream().write(buffer, 0, bytesRead); } inputStream.close(); } catch (Exception e) { log.error("获取文件内容失败!"); } } @Override public String getRelativePath(String path) { if (ObjectUtil.isEmpty(path)) { return null; } if (path.startsWith(this.localFilePath)) { return path.substring(this.localFilePath.length()); } return path; } @Override public String generateEduTrainingPdf(Map data) throws Exception { String filePath = getLocalFilePath(this.localFilePath, "edu", data.get("fileName").toString()); final ItextPdfTableVo pdfTableVo = PdfUtil.createTable(filePath, 6, 10); final Document document = pdfTableVo.getDocument(); final PdfWriter writer = pdfTableVo.getWriter(); final PdfPTable table = pdfTableVo.getTable(); final BaseFont fs = pdfTableVo.getFs(); final Font tableFont = pdfTableVo.getTableFont(); PdfUtil.dealHeader(document, fs, "学 习 教 育 记 录", 24); PdfUtil.dealEduBody(document, table, tableFont, data); document.close(); writer.close(); return filePath; } }