큰뼈대만 기록해둡니다.


파일입출력의 핵심은 DB에는 파일이 저장된 경로와 저장되었을때의 파일명과 원본 파일명을 기록해 두는것이다.

그리고 출력시에 ViewResolver의 순서를 InternalResourceViewResolver가 먼저가 아닌 BeanNameViewResolver의 순서를 우위에 두게 해서 빈객체 @Component("FileDownloadView")가 View객체로 사용되게 하는 것이다.


pom.xml

<!-- MultipartHttpServletRequset -->

<dependency>

    <groupId>commons-io</groupId>

    <artifactId>commons-io</artifactId>

    <version>2.0.1</version>

</dependency>

 

<dependency>

    <groupId>commons-fileupload</groupId>

    <artifactId>commons-fileupload</artifactId>

    <version>1.2.2</version>

</dependency>



MultipartHttpServletRequert를 실행하기 위해서 commons-io와 commons-fileupload를 maven에 추가합니다.



root-context.xml

<!-- File io -->

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

       <property name="maxUploadSize" value="100000000" />

       <property name="maxInMemorySize" value="100000000" />

</bean>



그리고 root-context에는 최대upload사이즈와  최대 메모리 사이즈를 지정해줍니다.



upLoad

@Component("AppUtils")

public class AppUtils {


private static final String filePath = "C:\\path";

    

    public List<Map<String,Object>> parseInsertFileInfo(Map<String,Object> map, HttpServletRequest request) throws Exception{

   

    MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest)request;

        Iterator<String> iterator = multipartHttpServletRequest.getFileNames();

       

        MultipartFile multipartFile = null;

        String originalFileName = null;

        String originalFileExtension = null;

        String storedFileName = null;

         

        List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();

        Map<String, Object> listMap = null;

         

        String boardIdx = (String)map.get("IDX");

         

        File file = new File(filePath);

        

        if(file.exists() == false){

            file.mkdirs();

        }

         

        while(iterator.hasNext()){

           

        multipartFile = multipartHttpServletRequest.getFile(iterator.next());

            

        if(multipartFile.isEmpty() == false){

                

        originalFileName = multipartFile.getOriginalFilename();

                originalFileExtension = originalFileName.substring(originalFileName.lastIndexOf("."));

                 

                Date dt = new Date();

                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");

                

                storedFileName = originalFileName + String.format("(%s)", sdf.format(dt)) + originalFileExtension;

                

                file = new File(filePath + storedFileName);

                

                //File transfer

                multipartFile.transferTo(file);

                 

                listMap = new HashMap<String,Object>();

                

                listMap.put("BOARD_IDX", boardIdx);

                listMap.put("ORIGINAL_FILE_NAME", originalFileName);

                listMap.put("STORED_FILE_NAME", storedFileName);

                listMap.put("FILE_SIZE", multipartFile.getSize());

                

                list.add(listMap);

            }

        }

        return list;

   

    }

   }




downLoad

 @RequestMapping(value="/board_detail/download", method = RequestMethod.GET)
     public ModelAndView downloadFile(@RequestParam("path") String FileName) throws Exception{
             
             String path = "C://dev//file";
             String FileFullPath = path + "//" + FileName;        
             java.io.File file = new java.io.File(FileFullPath);
      
             return new ModelAndView("FileDownloadView", "downloadFile", file );
     }


@Component("FileDownloadView")
public class FileDownloadView extends AbstractView {
   
    public FileDownloadView() {
        // TODO Auto-generated constructor stub
    }
   
    @Override
    protected void renderMergedOutputModel(Map<String, Object> map, HttpServletRequest req,
                                                                                                 HttpServletResponse res) throws Exception {
        // TODO Auto-generated method stub
       

try {
            File file = (File)map.get("downloadFile");
           
            res.setContentType(getContentType());
            res.setContentLength((int) file.length());
            res.setHeader("Content-Disposition", "attachment; filename=\""
                                                             + java.net.URLEncoder.encode(file.getName(), "utf-8") + "\";");
            res.setHeader("Content-Transfer-Encoding", "binary");
           
            OutputStream out = res.getOutputStream();
            FileInputStream fis = null;
           
            fis = new FileInputStream(file);
            FileCopyUtils.copy(fis, out);
           
            fis.close();
            out.flush();
           
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
   
}



'Programming > Spring' 카테고리의 다른 글

root-context & servlet-context  (0) 2018.02.14
ModelAndView 와 ViewResolver  (0) 2018.02.14
MariaDB Auto_Increment  (0) 2018.02.08
DAO, DTO, VO  (0) 2018.02.08
@Autowired, @Resource, @Inject  (0) 2018.02.05

+ Recent posts