Pages

2014년 11월 21일 금요일

[SPRING] HTTP 파일 전송

pom.xml 추가

1
2
3
4
5
6
7
8
9
10
11
12
<dependency>
    <groupId>commons-lang</groupId>
    <artifactId>commons-lang</artifactId>
    <version>2.6</version>
</dependency>
<dependency>
    <groupId>commons-httpclient</groupId>
    <artifactId>commons-httpclient</artifactId>
    <version>3.1</version>
</dependency>


* Maven 없을때 필요한 라이1브러리

- commons-codec-1.2.jar, commons-httpclient-3.1.jar, commons-lang-2.6.jar, commons-logging-1.1.1.jar


HttpFileRequestor 파일 전송 클래스


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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
public class HttpFileRequestor {
    private static final String DEFAULT_ENCODING = "UTF-8";
     
    private String url;
    private String encoding;
    private Map param;
     
     
    public HttpFileRequestor(String url){
        this(url, null);
    }
     
    public HttpFileRequestor(String url, String encoding){
        this.encoding = encoding==null ? DEFAULT_ENCODING : encoding;
        this.url = url;
         
        param = new HashMap();
    }
     
    /**
     * Http 전송
     * @return
     */
    public String submit(){
        String result = null;
         
        HttpClient client = new HttpClient();
        PostMethod method = new PostMethod (url);
        try{
            Part[] parts = new Part[param.size()];
            Iterator it = param.keySet().iterator();
            int index = 0;
            while( it.hasNext() ){
                String key = (String)it.next();
                Object value = param.get(key);
                 
                if( value instanceof File ){
                    // 한글 파일명 처리 위해 StringEscapeUtils 사용.
                    // 받는 쪽에서는 StringEscapeUtils.unescapeHtml() 로 다시 변환.
                    parts[index++] = new FilePart(
                                            key, 
                                            StringEscapeUtils.escapeHtml(((File)value).getName()), 
                                            (File)value, 
                                            null, 
                                            encoding);
                }else{
                    parts[index++] = new StringPart(key, (String)value, encoding);
                }
            }
            method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));
             
            client.executeMethod(method);
             
            // read result
            BufferedReader br = new BufferedReader(
                                        new InputStreamReader(method.getResponseBodyAsStream(), encoding));
            String buffer = null;
            StringBuffer tmp = new StringBuffer();
             
            while( (buffer=br.readLine())!=null ){
                tmp.append(buffer).append("\r\n");
            }
             
            result = tmp.toString();
        }catch (HttpException e) {
            e.printStackTrace();
        }catch (IOException e) {
            e.printStackTrace();
        }finally {
            method.releaseConnection();
        }
         
        return result;
    }
     
    /**
     * 일반 파라메터 추가
     * @param name  파라메터 이름
     * @param value 값
     * @return
     */
    public HttpFileRequestor addParam(String name, String value){
        param.put(name, value);
         
        return this;
    }
     
    /**
     * 업로드할 파일을 파라메터로 추가
     * @param name  <input type="file" name="요기들어가는 값"/>
     * @param file
     * @return
     */
    public HttpFileRequestor addParam(String name, File file){
        param.put(name, file);
         
        return this;
    }
    
}


파일을 전송하는 메소드

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
public UserProfileModel updateProfile(UserProfileModel userProfileModel, Long id, SessionUser sessionUser, HttpServletRequest request) {
        if (userProfileModel.getAttPhoto() != null) { // 모델 객체에서 파일있는지 확인
            String filePath = userProfileModel.getAttPhoto().getFilePath(); // 폼에서 전달받은 파일의 경로
            String[] _filePath;
            _filePath = filePath.split("/");
            // 폼에서 전달받은 파일을 실질적으로 프로젝트 폴더 내에 저장되어 있는 경로 확인
            String tempFilePath = appDirectory.getTempDirectoryWithYearWeek() + SLASH + _filePath[1]; 
            File tempFile = new File(tempFilePath); // 파일 객체에 경로입력
            // URL 가공
            String Url = request.getRequestURL().toString();
            String _Url = returnHost(Url);
            // 호출할 URL
            HttpFileRequestor http = new HttpFileRequestor(_Url + "/test/app/api/user/photoFile");
            // URL 파라미터 가공 후 호출
            http.addParam("userSeq",
                    String.valueOf(user.getMailUser().getMailUserSeq()))
                    .addParam(
                            "companySeq",
                            String.valueOf(user.getCompany().getMailDomain()
                                    .getMailDomainSeq()))
                    .addParam("upload_file", new File(tempFile.toString()))
                    .submit();
        }
    }

댓글 없음:

댓글 쓰기