Page tree

Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
languagejava
themeEmacs
titleupload
linenumberstrue
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
	static String ROOT_PATH = "C:\\workspace\\synapEditorsample\\out\\artifacts\\synapEditorsample_war_exploded";
	static String IMAGE_UPLOAD_DIR = "\\uploads";
    String fileName = file.getOriginalFilename();
    String ext = fileName.substring(fileName.lastIndexOf('.'));
    String saveFileName = UUID.randomUUID().toString() + ext;

    import javax.servlet.annotation.WebServlet;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.google.gson.Gson;
import com.google.gson.JsonObject;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet( name = "UploadServlet", urlPatterns = {"/uploadFile"} )
public class UploadServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;
    private static final String UPLOAD_DIRECTORY = "upload";
    private static final String DEFAULT_FILENAME = "default.file";
    
    private static final int MEMORY_THRESHOLD = 1024 * 1024 * 3;
    private static final int MAX_FILE_SIZE = 1024 * 1024 * 40;
    private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        if (ServletFileUpload.isMultipartContent(request)) {

            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setSizeThreshold(MEMORY_THRESHOLD);
            factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setFileSizeMax(MAX_FILE_SIZE);
            upload.setSizeMax(MAX_REQUEST_SIZE);
            String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;
            File uploadDir = new File(ROOT_PATH + IMAGE_UPLOAD_DIR);uploadPath);
            if (!uploadDir.exists()) {
                uploadDir.mkdirsmkdir();
            }

    byte[] bytes = file.getBytes();
    Path path = Paths.get(ROOT_PATH + IMAGE_UPLOAD_DIR        String fileName = "";
            try {
                List<FileItem> formItems = upload.parseRequest(request);

                if (formItems != null && formItems.size() > 0) {
                    for (FileItem item : formItems) {
                        if (!item.isFormField()) {
                            fileName = new File(item.getName()).getName();
                            String filePath = uploadPath + File.separator + saveFileName); fileName;
                            File storeFile = new File(filePath);
                          Files.write(path, bytes);

    Map<String, Object> map = new HashMap<>  item.write(storeFile);
                            request.setAttribute("message", "File " + fileName + " has uploaded successfully!");
                        }
                    }
                }
            } catch (Exception ex) {
                request.setAttribute("message", "There was an error: " + ex.getMessage());
            }
            
            Gson gson = new Gson();
            JsonObject obj = new JsonObject();
    map.put        obj.addProperty("uploadPath", "uploads/synapeditor/upload/" + saveFileName); fileName);
            String json = gson.toJson(obj);
            
            PrintWriter out = response.getWriter();
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            out.print(json);
           return map;
}out.flush();   
        }
    }
}

2. Importing MS Word / LibreOffice documents

Code Block
languagejava
themeEmacs
titleimport
linenumberstrue
@RequestMapping(value = "/importDoc", method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> importDoc(@RequestParam("file") MultipartFile importFile) throws IOException {
	static String ROOT_PATH = "C:\\workspace\\synapEditorsample\\out\\artifacts\\synapEditorsample_war_exploded";
	static String DOC_UPLOAD_DIR = "\\uploads\\docs";
	static String WORKS_DIR = "\\uploads\\tmp";
    String fileName = importFile.getOriginalFilename();

    File uploadDir = new File(DOC_UPLOAD_DIR);
    if(!uploadDir.exists()) {import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;
import java.util.zip.InflaterInputStream;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

@WebServlet( name = "ImportServlet", urlPatterns = {"/importDoc"} )
public class ImportServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;
    private static final String UPLOAD_DIRECTORY = "import";
    
    private static final int MEMORY_THRESHOLD = 1024 * 1024 * 3;
    private static final int MAX_FILE_SIZE = 1024 * 1024 * 40;
    private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        if (ServletFileUpload.isMultipartContent(request)) {

            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setSizeThreshold(MEMORY_THRESHOLD);
            factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setFileSizeMax(MAX_FILE_SIZE);
            upload.setSizeMax(MAX_REQUEST_SIZE);
            String  uploadDir.mkdirs()uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;
    }        
            byte[]File bytesstoreFile = new byte[0];null;
            try {
                List<FileItem> bytesformItems = importFileupload.getBytesparseRequest(request);

                if (formItems != null && formItems.size() > 0) {
                 }   catchfor (IOException eFileItem item : formItems) {
             e.printStackTrace();           if (!item.isFormField()) {
                       }     PathString pathfileName = Paths.get(DOC_UPLOAD_DIR + "\\" + fileName);new File(item.getName()).getName();
                            String filePath = uploadPath + File.separator + fileName;
                            storeFile = new File(filePath);
           try {                 Files.write(path, bytes);
    } catch (IOException eitem.write(storeFile);
                            request.setAttribute("message", "File " + fileName + " has uploaded successfully!");
                        }
                    }
                }
            } catch (Exception ex) {
        e.printStackTrace();        request.setAttribute("message", "There was an error: " + ex.getMessage());
            }
            
            // 월별로 파일 변환
            Calendar cal = Calendar.getInstance();
            String yearMonth = String.format("%04d%02d", cal.get(Calendar.YEAR), cal.get(Calendar.MONTH)+1);
         File worksDir   
            // 파일별로 변환결과를 저장할 경로 생성
            String uuid = UUID.randomUUID().toString();
            
            // 경로 생성
            File outputPath = new File(ROOT_PATHuploadPath + File.separator + yearMonth + File.separator + WORKS_DIRuuid);
            if(!worksDiroutputPath.exists()) {
            worksDir	outputPath.mkdirs();
            }
            
            // 변환 실행
     executeConverter(DOC_UPLOAD_DIR + File.separator + fileName, ROOT_PATH + WORKS_DIR);       executeConverter(storeFile.getAbsolutePath(), outputPath.getAbsolutePath());
            
            // 변환된 pb파일을 읽어서 serialzie
            Integer[] serializedData = serializePbData(WORKS_DIR(outputPath + "/document.word.pb");
            
            // pb파일 삭제
            File pbFile = new File(outputPath + "\\/document.word.pb");
            pbFile.deleteOnExit();

            // return data를 map으로 구성
            Map<String, Object> map = new HashMap<>();
            map.put("serializedData", serializedData);
            map.put("importPath", WORKS_DIR); "/synapeditor/import/" + yearMonth + "/" + uuid);
            
            // json 형태로 return (google gson lib 사용)
            Gson gson = new GsonBuilder().create();
            PrintWriter out = response.getWriter();
            out.print(gson.toJson(map));
            out.flush();
        }
    }
 
public
    
    protected static voidint executeConverter(String inputFilePath, String outputFilePathoutputPath) {
        String SEDOC_CONVERT_DIR = "C:\\sedocConverter\\sedocConverter./workspace/workspace-sts/synapeditor/WebContent/WEB-INF/sedocConverter/sedocConverter_exe";
        String FONT_DIR = "C:\\sedocConverter\\sedocConverter\\/workspace/workspace-sts/synapeditor/WebContent/WEB-INF/sedocConverter/fonts";
        String TEMP_DIR = "C:\\sedocConverter\\sedocConverter\\/workspace/workspace-sts/synapeditor/WebContent/WEB-INF/sedocConverter/tmp";

        File tempDir = new File(TEMP_DIR);
        if(!tempDir.exists()) {
            tempDir.mkdirs();
        }

        File fontDir = new File(FONT_DIR);
        if(!fontDir.exists()) {
            fontDir.mkdirs();
    }    }
 Runtime rt = Runtime.getRuntime();    
Process process;      try {// 변환 명령 구성
     process = rt.exec(new String[] cmd = {SEDOC_CONVERT_DIR, "-f", FONT_DIR, inputFilePath, outputFilePathoutputPath, TEMP_DIR};
        try {
            Timer t = new Timer();
            Process proc = Runtime.getRuntime().exec(cmd);

            TimerTask killer = new TimeoutProcessKiller(proc);
            t.schedule(killer, 20000); // 20초 (변환이 20초 안에 완료되지 않으면 프로세스 종료)

        process.waitFor    int exitValue = proc.waitFor();
            killer.cancel();

            return exitValue;
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
    }

    publicprotected static Integer[] serializePbData(String pbFilePath) throws IOException {
        List<Integer> serializedData = new ArrayList<Integer>();
        FileInputStream fis = new FileInputStream(pbFilePath);

        Integer[] data = null;

        fis.skip(16);

        InflaterInputStream ifis = new InflaterInputStream(fis);

        byte[] buffer = new byte[1024];

        int len = -1;
        while ((len = ifis.read(buffer)) != -1) {
            for (int i = 0; i < len; i++) {
                serializedData.add(buffer[i] & 0xFF);
            }
        }

        data = serializedData.toArray(new Integer[serializedData.size()]);

        ifis.close();
        fis.close();

        return data;
    }
    
}