Browse Source

测试导出文件1

zhuoning 3 years ago
parent
commit
375b5c7c44

+ 11 - 3
huimv-manage/pom.xml

@@ -86,14 +86,12 @@
             <version>1.4.7</version>
         </dependency>
 
-
         <dependency>
             <groupId>commons-httpclient</groupId>
             <artifactId>commons-httpclient</artifactId>
             <version>3.1</version>
         </dependency>
 
-
         <dependency>
             <groupId>org.apache.ws.commons.axiom</groupId>
             <artifactId>axiom-api</artifactId>
@@ -142,7 +140,6 @@
             <version>1.6.1</version>
         </dependency>
 
-
         <dependency>
             <groupId>com.alibaba</groupId>
             <artifactId>fastjson</artifactId>
@@ -237,6 +234,17 @@
             <artifactId>poi-ooxml-schemas</artifactId>
             <version>3.17</version>
         </dependency>
+
+        <dependency>
+            <groupId>commons-io</groupId>
+            <artifactId>commons-io</artifactId>
+            <version>2.8.0</version>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.commons</groupId>
+            <artifactId>commons-compress</artifactId>
+            <version>1.9</version>
+        </dependency>
     </dependencies>
 
     <build>

+ 5 - 4
huimv-manage/src/main/java/com/huimv/manage/eartag/controller/EarmarkController.java

@@ -4,6 +4,7 @@ import com.huimv.manage.eartag.service.IEarmarkService;
 import com.huimv.manage.util.Result;
 import com.huimv.manage.webservice.task.EarmarkTask;
 import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.compress.archivers.ArchiveException;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.web.bind.annotation.*;
@@ -150,18 +151,18 @@ public class EarmarkController {
     public void exportEarmarkByApply(@RequestParam(value = "applyId",required = true) Integer applyId,
                                      @RequestParam(value = "printState",required = false) Integer printState,
                                      @RequestParam(value = "quantity",required = true) Integer quantity,
-                                     HttpServletResponse response) throws IOException {
+                                     HttpServletResponse response,HttpServletRequest request) throws IOException, ArchiveException {
         log.info("applyId="+applyId);
         log.info("printState="+printState);
         log.info("quantity="+quantity);
-        //
+        //导出数据到excel格式
 //        earmarkService.exportEarmarkByApply(applyId,printState,quantity,response);
         //导出数据到文本文件中
 //        earmarkService.exportEarmarkByApplyToTxt(applyId,printState,quantity,response);
         //test1
-        earmarkService.exportTest1(applyId,printState,quantity,response);
+        earmarkService.exportTest1(applyId,printState,quantity,response,request);
         //test2
-//        earmarkService.exportTest2(applyId,printState,quantity,response);
+//        earmarkService.exportTest2(applyId,printState,quantity,response,request);
     }
 
     /**

+ 5 - 2
huimv-manage/src/main/java/com/huimv/manage/eartag/service/IEarmarkService.java

@@ -1,8 +1,11 @@
 package com.huimv.manage.eartag.service;
 
 import com.huimv.manage.util.Result;
+import org.apache.commons.compress.archivers.ArchiveException;
 
+import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
+import java.io.FileNotFoundException;
 import java.io.IOException;
 import java.io.UnsupportedEncodingException;
 import java.util.Date;
@@ -36,7 +39,7 @@ public interface IEarmarkService {
     //通过耳标号导出耳标数据到文本文件
     void exportEarmarkByApplyToTxt(Integer applyId, Integer printState, Integer quantity, HttpServletResponse response);
 
-    void exportTest1(Integer applyId, Integer printState, Integer quantity, HttpServletResponse response);
+    void exportTest1(Integer applyId, Integer printState, Integer quantity, HttpServletResponse response, HttpServletRequest request) throws IOException, ArchiveException;
 
-    void exportTest2(Integer applyId, Integer printState, Integer quantity, HttpServletResponse response);
+    void exportTest2(Integer applyId, Integer printState, Integer quantity, HttpServletResponse response, HttpServletRequest request) throws IOException;
 }

+ 227 - 25
huimv-manage/src/main/java/com/huimv/manage/eartag/service/impl/EarmarkServiceImpl.java

@@ -9,6 +9,7 @@ import com.huimv.manage.util.*;
 import com.huimv.manage.webservice.Soap;
 import com.huimv.manage.webservice.task.EarmarkTask;
 import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.io.FileUtils;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.data.domain.Example;
@@ -16,19 +17,29 @@ import org.springframework.data.domain.ExampleMatcher;
 import org.springframework.data.domain.PageRequest;
 import org.springframework.data.domain.Pageable;
 import org.springframework.data.jpa.domain.Specification;
+import org.springframework.http.HttpHeaders;
 import org.springframework.stereotype.Service;
+import org.springframework.util.ResourceUtils;
+import org.springframework.util.StringUtils;
 
 import javax.persistence.criteria.Order;
 import javax.persistence.criteria.Predicate;
 import javax.servlet.ServletOutputStream;
+import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
-import java.io.BufferedOutputStream;
-import java.io.IOException;
-import java.io.UnsupportedEncodingException;
+import java.io.*;
 import java.net.URLEncoder;
 import java.sql.Timestamp;
 import java.util.*;
 
+import org.apache.commons.compress.archivers.ArchiveException;
+import org.apache.commons.compress.archivers.ArchiveOutputStream;
+import org.apache.commons.compress.archivers.ArchiveStreamFactory;
+import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
+import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
+//import org.apache.tomcat.util.http.fileupload.FileUtils;
+import org.apache.commons.io.FileUtils;
+
 /**
  * @Project : huimv.shiwan
  * @Package : com.huimv.biosafety.uface.controller
@@ -52,6 +63,8 @@ public class EarmarkServiceImpl implements IEarmarkService {
     private CodeUtil codeUtil;
     @Autowired
     private ExcelUtil excelUtil;
+    @Autowired
+    private DataUtil dateUtil;
 
     /**
      * @Method      : listEarmark
@@ -381,34 +394,223 @@ public class EarmarkServiceImpl implements IEarmarkService {
     }
 
     @Override
-    public void exportTest1(Integer applyId, Integer printState, Integer quantity, HttpServletResponse response) {
-        String fileName = "fileName" + ".txt";
-        String content = "写入txt的内容";
-        response.setContentType("text/plain");
-
-        try {
-            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
-        } catch (UnsupportedEncodingException e) {
-            e.printStackTrace();
+    public void exportTest1(Integer applyId, Integer printState, Integer quantity, HttpServletResponse response, HttpServletRequest request) throws IOException, ArchiveException {
+//        String fileName = "fileName" + ".txt";
+//        String content = "写入txt的内容";
+//        response.setContentType("text/plain");
+//
+//        try {
+//            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
+//        } catch (UnsupportedEncodingException e) {
+//            e.printStackTrace();
+//        }
+//
+//        ServletOutputStream outputStream = null;
+//        BufferedOutputStream buffer = null;
+//
+//        try {
+//            outputStream = response.getOutputStream();
+//            buffer = new BufferedOutputStream(outputStream);
+//            buffer.write(content.getBytes("UTF-8"));
+//            buffer.flush();
+//            buffer.close();
+//            outputStream.close();
+//        } catch (IOException e) {
+//            e.printStackTrace();
+//        }
+        //定义根路径
+        //Linux
+//        String rootPath = request.getRealPath("/");
+        //Windows
+        String rootPath = "D:\\";
+        String basePath = rootPath + "temp_download";
+        System.out.println("basePath>>"+basePath);
+        //创建文件
+        File file = new File(basePath);
+        //判断文件是否存在,如果不存在,则创建此文件夹
+        if (!file.exists()) {
+            file.mkdir();
         }
 
-        ServletOutputStream outputStream = null;
-        BufferedOutputStream buffer = null;
-
-        try {
-            outputStream = response.getOutputStream();
-            buffer = new BufferedOutputStream(outputStream);
-            buffer.write(content.getBytes("UTF-8"));
-            buffer.flush();
-            buffer.close();
-            outputStream.close();
-        } catch (IOException e) {
-            e.printStackTrace();
+//        String basePath = getResourceBasePath(request);
+//        System.out.println("basePath>>"+basePath);
+//        String studentResourcePath = new File(basePath, "student/student.txt").getAbsolutePath();
+        File txtFile1 = new File(basePath, "eartag\\earmark_1.txt");
+        System.out.println("txtFile1.exists()>>"+txtFile1.exists());
+//        String studentResourcePath = txtFile1.getAbsolutePath();
+//        System.out.println("studentResourcePath = " + studentResourcePath);
+        // 保证目录一定存在
+//        ensureDirectory(studentResourcePath);
+
+//        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(studentResourcePath)));
+////        for (Student student : students) {
+////            StringBuffer buffer = new StringBuffer();
+////            buffer.append(student.getName());
+////            buffer.append("\t");
+////            buffer.append(student.getAge());
+////            buffer.append("\t");
+////            buffer.append(student.getSex());
+////            buffer.append("\r\n");
+////            writer.write(buffer.toString());
+////        }
+//        String text = "测试内容";
+//        writer.write(text);
+//        writer.flush();
+//        writer.close();
+        File txtFile2 = new File(basePath, "eartag/earmark_2.txt");
+        System.out.println("txtFile2.exists()>>"+txtFile2.exists());
+        File txtFile3 = new File(basePath, "eartag/earmark_3.txt");
+        System.out.println("txtFile3.exists()>>"+txtFile3.exists());
+        List<File> fileList = new ArrayList();
+        fileList.add(txtFile1);
+        fileList.add(txtFile2);
+        fileList.add(txtFile3);
+
+//        String fileName = "耳标数据下载" + "_" + dateUtil.formatLongTimeForTime(new Date().getTime());
+        String fileName = "耳标数据下载";
+        String zipFileName = fileName + ".zip";
+        System.out.println("zipFileName>>"+zipFileName);
+
+        File filex = new File(basePath + "\\newFile.txt");
+        System.out.println("###### filex.exists>>"+filex.exists());
+        String resourcePath = txtFile1.getAbsolutePath();
+        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(resourcePath)));
+        String text = "测试内容";
+        writer.write(text);
+        writer.flush();
+        writer.close();
+
+        // 打成压缩包
+//        File zipFile = null;
+        String zipPath = basePath + "\\eartag\\" + zipFileName;
+        System.out.println("zipPath>>"+zipPath);
+        File zipFile = new File(zipPath);
+        System.out.println("zipFileexists.exists>>"+zipFile.exists());
+        FileOutputStream zipFos = new FileOutputStream(zipFile);
+        ArchiveOutputStream archOut = new ArchiveStreamFactory().createArchiveOutputStream(ArchiveStreamFactory.ZIP, zipFos);
+        if (archOut instanceof ZipArchiveOutputStream) {
+            ZipArchiveOutputStream zos = (ZipArchiveOutputStream) archOut;
+            for (File fileFile : fileList) {
+                ZipArchiveEntry zipEntry = new ZipArchiveEntry(fileFile, fileFile.getName());
+                zos.putArchiveEntry(zipEntry);
+                zos.write(FileUtils.readFileToByteArray(fileFile));
+                zos.closeArchiveEntry();
+                zos.flush();
+            }
+            zos.close();
+        }
+        // 输出到客户端
+        OutputStream out = null;
+        out = response.getOutputStream();
+        response.reset();
+        response.setHeader("Content-Disposition", "attachment;filename=" + new String(zipFileName.getBytes("GB2312"), "ISO-8859-1"));
+        response.setContentType("application/octet-stream; charset=utf-8");
+        response.setCharacterEncoding("UTF-8");
+        out.write(FileUtils.readFileToByteArray(zipFile));
+        out.flush();
+        out.close();
+        // 输出客户端结束后,删除压缩包
+        if (zipFile.exists()) {
+            zipFile.delete();
         }
     }
 
     @Override
-    public void exportTest2(Integer applyId, Integer printState, Integer quantity, HttpServletResponse response) {
+    public void exportTest2(Integer applyId, Integer printState, Integer quantity, HttpServletResponse response, HttpServletRequest request) throws IOException {
+        String basePath = getResourceBasePath(request);
+        System.out.println("basePath>>"+basePath);
+//        String studentResourcePath = new File(basePath, "student/student.txt").getAbsolutePath();
+        File txtFile = new File(basePath, "eartag/earmark_1.txt");
+        String studentResourcePath = txtFile.getAbsolutePath();
+        System.out.println("studentResourcePath = " + studentResourcePath);
+        // 保证目录一定存在
+        ensureDirectory(studentResourcePath);
 
+        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(studentResourcePath)));
+//        for (Student student : students) {
+//            StringBuffer buffer = new StringBuffer();
+//            buffer.append(student.getName());
+//            buffer.append("\t");
+//            buffer.append(student.getAge());
+//            buffer.append("\t");
+//            buffer.append(student.getSex());
+//            buffer.append("\r\n");
+//            writer.write(buffer.toString());
+//        }
+        String text = "测试内容";
+        writer.write(text);
+        writer.flush();
+        writer.close();
+
+        response.setHeader("content-type", "application/octet-stream");
+        response.setContentType("application/octet-stream");
+        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=download.zip");
+        //
+        ZipUtils.downloadZip(response.getOutputStream(), txtFile);
     }
+
+    /**
+     * 获取项目根路径
+     *
+     * @return
+     */
+    private static String getResourceBasePath(HttpServletRequest request) {
+//        // 获取跟目录
+//        File path = null;
+//        try {
+//            path = new File(ResourceUtils.getURL("classpath:").getPath());
+//        } catch (FileNotFoundException e) {
+//            // nothing to do
+//        }
+//        if (path == null || !path.exists()) {
+//            path = new File("");
+//        }
+//
+//        String pathStr = path.getAbsolutePath();
+//        // 如果是在eclipse中运行,则和target同级目录,如果是jar部署到服务器,则默认和jar包同级
+//        pathStr = pathStr.replace("\\target\\classes", "");
+
+        //定义根路径
+        String rootPath = request.getRealPath("/");
+        //创建文件
+        File file = new File(rootPath + "temp_download");
+        //判断文件是否存在,如果不存在,则创建此文件夹
+        if (!file.exists()) {
+            file.mkdir();
+        }
+        String pathStr = file.getAbsolutePath();
+        System.out.println("pathStr>>"+pathStr);
+        return pathStr;
+    }
+
+    /**
+     * 保证拷贝的文件的目录一定要存在
+     *
+     * @param filePath
+     *            文件路径
+     */
+    public static void ensureDirectory(String filePath) {
+        if (StringUtils.isEmpty(filePath)) {
+            return;
+        }
+        filePath = replaceSeparator(filePath);
+        if (filePath.indexOf("/") != -1) {
+            filePath = filePath.substring(0, filePath.lastIndexOf("/"));
+            File file = new File(filePath);
+            if (!file.exists()) {
+                file.mkdirs();
+            }
+        }
+    }
+
+    /**
+     * 将符号“\\”和“\”替换成“/”,有时候便于统一的处理路径的分隔符,避免同一个路径出现两个或三种不同的分隔符
+     *
+     * @param str
+     * @return
+     */
+    public static String replaceSeparator(String str) {
+        return str.replace("\\", "/").replace("\\\\", "/");
+    }
+
 }

+ 32 - 0
huimv-manage/src/main/java/com/huimv/manage/util/DataUtil.java

@@ -2,6 +2,8 @@ package com.huimv.manage.util;
 
 import org.springframework.stereotype.Component;
 
+import java.sql.Timestamp;
+import java.text.DateFormat;
 import java.text.ParseException;
 import java.text.SimpleDateFormat;
 import java.util.Date;
@@ -29,4 +31,34 @@ public class DataUtil {
         SimpleDateFormat sdfmat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
         return sdfmat.parse(sdfmat.format(sdf.parse(dateTime).getTime()));
     }
+
+    public String formatLongTime(Long dateLong){
+        Date date =new Date(dateLong);//以1429339937748为bai毫秒数du实例化zhi一个Date对象dao
+        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");//设置转化格式
+        String time=sdf.format(date);//将Date对象转化为yyyy-MM-dd形式的字符串zhuan
+        System.out.println(time);//输出字符串
+        return time;
+    }
+
+    public String formatLongTimeForTime(Long dateLong){
+        Date date =new Date(dateLong);//以1429339937748为bai毫秒数du实例化zhi一个Date对象dao
+        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss");//设置转化格式
+        String time=sdf.format(date);//将Date对象转化为yyyy-MM-dd形式的字符串zhuan
+        System.out.println(time);//输出字符串
+        return time;
+    }
+
+    public String formatTimestamp(Timestamp timestamp) {
+        DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+        //方法一
+        return sdf.format(timestamp);
+    }
+
+    public String formatLongTimeToImageName(Long dateLong){
+        Date date =new Date(dateLong);//以1429339937748为bai毫秒数du实例化zhi一个Date对象dao
+        SimpleDateFormat sdf=new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");//设置转化格式
+        String time=sdf.format(date);//将Date对象转化为yyyy-MM-dd形式的字符串zhuan
+        System.out.println(time);//输出字符串
+        return time;
+    }
 }

+ 57 - 0
huimv-manage/src/main/java/com/huimv/manage/util/ZipUtils.java

@@ -0,0 +1,57 @@
+package com.huimv.manage.util;
+
+import java.io.*;
+import java.util.List;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipOutputStream;
+
+/**
+ * @Project : huimv.shiwan
+ * @Package : com.huimv.biosafety.uface.controller
+ * @Description : TODO
+ * @Version : 1.0
+ * @Author : ZhuoNing
+ * @Create : 2020-12-25
+ **/
+public class ZipUtils {
+
+    public static void downloadZip(OutputStream outputStream, File file){
+        BufferedInputStream bufferedInputStream = null;
+        ZipOutputStream zipOutputStream = null;
+        try {
+            zipOutputStream = new ZipOutputStream(outputStream);
+//            for (File file : fileList) {
+                ZipEntry zipEntry = new ZipEntry(file.getName());
+                zipOutputStream.putNextEntry(zipEntry);
+                byte[] buf = new byte[1024];
+                int len;
+                FileInputStream in = new FileInputStream(file);
+                while ((len = in.read(buf)) != -1) {
+                    zipOutputStream.write(buf, 0, len);
+                    zipOutputStream.flush();
+                }
+//            }
+            zipOutputStream.flush();
+            zipOutputStream.close();
+
+        } catch (IOException e) {
+            e.printStackTrace();
+        } finally {
+            // 关闭流
+            try {
+                if (bufferedInputStream != null) {
+                    bufferedInputStream.close();
+                }
+                if (zipOutputStream != null ) {
+                    zipOutputStream.close();
+                }
+                if (outputStream != null) {
+                    outputStream.close();
+                }
+            } catch (IOException e) {
+                e.printStackTrace();
+            }
+        }
+
+    }
+}

+ 1 - 0
huimv-manage/src/main/resources/application.properties

@@ -1,3 +1,4 @@
+#spring.profiles.active=dev
 spring.profiles.active=public
 
 #���ӳ�