spring Framework 파일 업로드

Posted by 백창
2014. 9. 29. 13:54 개발/Spring
반응형


 개요


 Spring에서 파일 업로드를 처리해보자



 설정


servlet_context.xml 파일 설정


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<!-- 파일저장 -->
    <bean id="uploadPathResource" class="org.springframework.core.io.FileSystemResource">
        <constructor-arg>
            <value>D:\R\work\demo\file\</value>
        </constructor-arg>
    </bean>
    
    <!-- Upload File Size Definition -->
    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize">
        <!-- 파일 업로드 최대 용량 단위 byte -->
            <value>10485677</value>
        </property>
    </bean>




 소스


UploadItem.java 파일


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package com.nara.comm;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
 
public class UploadItem
{
  private CommonsMultipartFile fileData;
  private String name;
  
  public String getName(){
      return name;
  }
  
  public void setName(String name){
      this.name = name;
  }
  
  public CommonsMultipartFile getFileData()
  {
    return fileData;
  }
 
  public void setFileData(CommonsMultipartFile fileData)
  {
    this.fileData = fileData;
  }
}


Controller 파일


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
 
import org.springframework.core.io.FileSystemResource;
import org.springframework.validation.BindingResult;
import com.nara.demo.UploadItem;
 
@Inject private FileSystemResource uploadFilePath;
 
public void getFileName(@RequestParam Map<String, Object> paramMap, ModelMap model,UploadItem uploadItem, BindingResult result) throws Throwable{
        
        String getFileName = "";
        
        date = dateFormat.format(System.currentTimeMillis());
        
        if (result.hasErrors()){
            for(ObjectError error : result.getAllErrors()){
                System.err.println("Error: " + error.getCode() +  " - " + error.getDefaultMessage());
            }
        }
 
        if(!uploadItem.getFileData().isEmpty()){
            
            fileName = date+"_"+uploadItem.getFileData().getOriginalFilename();
            String fileExt = fileName.substring(fileName.lastIndexOf(".")+1, fileName.length());
            
            //upload 가능한 파일 타입 지정
            if(fileExt.equalsIgnoreCase("csv")){
                byte[] bytes = uploadItem.getFileData().getBytes();
                try{
                    File lOutFile = new File(uploadFilePath.getPath()+fileName);
                    FileOutputStream lFileOutputStream = new FileOutputStream(lOutFile);
                    lFileOutputStream.write(bytes);
                    lFileOutputStream.close();
                }catch(IOException ie){
                    //Exception 처리
                    System.err.println("File writing error! ");
                }
                System.err.println("File upload success! ");
            }else{
                System.err.println("File type error! ");
            }
            model.put("fileName",fileName);
        }
 
        // Some type of file processing...
        System.err.println("upload path : " + uploadFilePath.getPath());
        System.err.println("upload fileName: " + fileName);
}




view 부분


1
2
3
4
5
6
7
8
9
10
11
12
            <form name="aform" method="post" enctype="multipart/form-data">
            <table width="231" border="0" cellpadding="0" cellspacing="0">
                Choose the File<br>
                <input type="file" id="fileData" name="fileData"  /><br><br>
    <!--             onchange="javascrpit:document.getElementById('fileName').value = this.value" -->
<!--                 <input type="button" id="searchFile" name="searchFile" value="파일 찾기" /> -->
                <input type="button" value="show" onclick="fnShow()" />
                
                
            </table>
            
        </form>



 Form 으로 감싸는 부분에서 enctype="multipart/form-data" 를 추가해야 파일 데이터가 Post방식으로 전송 된다.


 결과


파일 업로드


파일 업로드 목록



반응형

'개발 > Spring' 카테고리의 다른 글

[myBatis] selectKey 사용  (0) 2014.09.03