티스토리 뷰

728x90
반응형

안드로이드에서 사진 또는 파일을 업로드 하는 기능은 매우 흔하게 볼수 있는 사례입니다.


HttpClient 라이브러리를 통해서 http를 이용해 원격지의 서버로 파일을 업로드하는 기능을 매우 쉽게 구현할 수 있습니다.


http://hc.apache.org/downloads.cgi





이 사이트에서 HttpClient 4.2.2를 다운받습니다.


파일의 압축을 풀어서 lib 폴더에 들어가면 아래와 같이 여러개의 라이브러리 파일이 보이는데요.




우리가 필요한것은


httpclient-4.2.2.jar

httpcore-4.2.2.jar

httpmime-4.2.2.jar


이렇게 세개의 파일입니다.



이 세개의 파일을 안드로이드 프로젝트로 import 해주시면 준비 끝.



이제 파일 업로드 기능을 구현해 볼까요.


기존 httppost 전송코드에


MultipartEntity 인스턴스를 생성하여 httppost에 entity를 추가해주면 됩니다.


HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);

MultipartEntity reqEntity = new MultipartEntity();
File file = new File("file.png");
reqEntity.addPart("attachment", new FileBody(file));
httppost.setEntity(reqEntity);

HttpResponse response = httpclient.execute(httppost);


파일과 함께 다른 문자열 데이터도 함께 보낸다면 MultipartEntiry에 역시 추가해줍니다.


HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);

MultipartEntity reqEntity = new MultipartEntity();
File file = new File("file.pdf");
reqEntity.addPart("attachment", new FileBody(file));
reqEntity.addPart("name", new StringBody("value", Charset.forName("UTF-8")));
httppost.setEntity(reqEntity);

HttpResponse response = httpclient.execute(httppost);


이렇게 보낸 데이터를 서버에서 수신할때는 (PHP의 예를 들면)



기존 웹업로드시 처리방식과 동일하게 $_FILES['attachment'] 를 통해 파일을 받고,


문자열은 $_POST['name'] 를 통해서 수신할 수 있습니다.



<?php
print_r($_POST);
print_r($_FILES);
?>



결과

Array
(
    [name] => value
)
Array
(
    [attachment] => Array
        (
            [name] => file.pdf
            [type] => application/octet-stream
            [tmp_name] => /tmp/phpRROpzf
            [error] => 0
            [size] => 5011525
        )

)


728x90
반응형
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/03   »
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
글 보관함