본문 바로가기

6. With IT/6.1 Android

파일전송(웹 서버 : 아파치서버)


아......'무'에서 '유'를 창조하려니 참 쉽지 않네....


이번에는 웹서버상에 파일을 전송하는 내용을 적어놓아야겠다.


원래 의도는 asp상에서 파일을 업로드 하려 했건만, 자료가 많이 있지가 않다.....ㅡㅡ;;;


그래서 부랴부랴 컴에 톰캣을 깔고 웹서버로 안드로이드 어플상에서 파일을 전송하는 포스팅을 한다.


===================================================================================================================

1. 먼저 톰캣 서버 설치부분

: 알아서들 하도록. 포스팅 한 곳이 무지하게 많다.


2. 톰캣을 설치하고나면 특정 파일(*.jsp)을 기본 페이지로 설정하고 쓸 것이다.  그 내용이다. 

<UploadFileWeb.jsp>


<FORM action="http://server.com/cgi/handle"

       enctype="multipart/form-data"

       method="post">

  

 </FORM>

 

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ page import="com.oreilly.servlet.*, com.oreilly.servlet.multipart.*" %>

<%@ page import="java.io.*, java.util.*" %>

<%


    // 먼저 파일이 저장될 서버의 실제 폴더 경로를 구합니다.. ServletContext 객체를 이용합니다.

    String realFolder = "";

    // webApps 상의 폴더명입니다.. 이 폴더에 해당하는 실제 경로를 찾아서  realFolder 로 매핑시킵니다.

    String saveFolder = "fileSave";

    String charset = "euc-kr";

    int maxSize = 1024 * 1024 * 1024;

    

    realFolder = this.getServletContext().getRealPath(saveFolder);

    out.println("다음 경로에 파일이 저장됩니다.  : " + realFolder);

    

    try {

        // 이제부터 multipartRequest 객체를 이용해서 파일을 업로드 합니다.

        MultipartRequest multi = null;

        multi = new MultipartRequest(request, realFolder, maxSize, charset, 

                new DefaultFileRenamePolicy());

        // 이상으로 파일 업로드 끝..

        

        // 이제부터 Form에서 전송되는 파라미터 확인 해 봅니다.

        Enumeration<String> params = multi.getParameterNames();

        

        while (params.hasMoreElements()) {

            String name = params.nextElement();

            String value = multi.getParameter(name);

            out.println("<br />" + name + " : " + value + "<br />");

        }

        

        out.println("<hr color='red' />");

        out.println("업로드 된 파일의 정보");

        

        Enumeration files = multi.getFileNames();

        

        while (files.hasMoreElements()) {

            String name = (String)files.nextElement();

            String fileName = multi.getFilesystemName(name);

            String originName = multi.getOriginalFileName(name);

            String type = multi.getContentType(name);

            

            // 전송된 파일의 실제 속성을 열여봅니다..

            File file = multi.getFile(name);

            

            out.println("파라미터의 이름 : " + name + "<br />");

            out.println("실제 파일 이름 : " + originName + "<br />");

            out.println("저장된 파일 이름 : " + fileName + "<br />");

            out.println("파일타입 : " + type + "<br />");

            

            if (file != null) {

                out.println("크기 : " + file.length());

                out.println("<br />");

            }

        }

    } catch (Exception e) {

        e.printStackTrace();

    }

%> 


[@주의! : 

1."java.io.IOException: Posted content type isn't multipart/form-data"라는 개소리가 뜰 것이다. 정 궁금하다면,

<출처 :http://flashcafe.org/asp_study/3892 >를 보시라~~~.

나도 어떻게 해결해야하는지는 웹 프로그래밍은 많이 안해봐서 모르겠다.ㅠㅠㅠㅠㅠㅠㅠㅠㅠ(아시는 분 답변좀~~)


2. 서블릿 관련 에러Caused by: java.lang.NoSuchMethodError: javax.servlet.ServletContext.getContextPath()Ljava/lang/String;)가 나면,

C:\Program Files\Apache Software Foundation\Tomcat 6.0\lib\servlet-api.jar 파일을

C:\Program Files\Java\jre7\lib\ext로 복사하고, 이클립스를 다시 실행시켜라.

(각자 디렉토리에있는 톰캣 버전의 servlet-api.jar를 복사해야한다. 경로와 패스는 알아서 고쳐서 써라.)]



2. 다음, 안드로이드 소스 부분이다. 여기서 주의해야 할 것은, 이것 역시 파일 전송 관련코드이기 때문에 StrictMode(이전 '안드로이드 파일 ftp전송'참고)를 사용해야 한다는 것이다. 


<MainActivity.java>


...


String lineEnd = "\r\n";

String twoHyphens = "--";

String boundary = "*****";

...

protected void onCreate(Bundle savedInstanceState) {

...

HttpFileUpload("http://58.102.122.159:8080/hello/UploadFileWeb.jsp" , "" , "/storage/sdcard0/Desert.jpg");

...

}

...

private boolean HttpFileUpload(String urlString , String sTalk, String fileName) {

try {

mFileInputStream = new FileInputStream(fileName);

connectUrl = new URL(urlString);

// open connection 

HttpURLConnection conn = (HttpURLConnection)connectUrl.openConnection();

conn.setDoInput(true);

conn.setDoOutput(true);

conn.setUseCaches(false);

//conn.setRequestMethod("GET");

conn.setRequestMethod("POST");

conn.setRequestProperty("Connection", "Keep-Alive");

conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

// write data

DataOutputStream dos = new DataOutputStream(conn.getOutputStream());

dos.writeBytes(twoHyphens + boundary + lineEnd);

dos.writeBytes("Content-Disposition: form-data; name=\"stalk\"" + lineEnd);

dos.writeBytes(sTalk + lineEnd);

dos.writeBytes(lineEnd);

dos.writeBytes(twoHyphens + boundary + lineEnd);

dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + fileName+"\"" + lineEnd);

dos.writeBytes(lineEnd);

int bytesAvailable = mFileInputStream.available();

int maxBufferSize = 1024;

int bufferSize = Math.min(bytesAvailable, maxBufferSize);

byte[] buffer = new byte[bufferSize];

int bytesRead = mFileInputStream.read(buffer, 0, bufferSize);

// read image

while (bytesRead > 0) {

dos.write(buffer, 0, bufferSize);

bytesAvailable = mFileInputStream.available();

bufferSize = Math.min(bytesAvailable, maxBufferSize);

bytesRead = mFileInputStream.read(buffer, 0, bufferSize);

}

dos.writeBytes(lineEnd);

dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

// close streams

mFileInputStream.close();

dos.flush(); // finish upload...

// get response

int ch;

InputStream is = conn.getInputStream();

StringBuffer b =new StringBuffer();

while( ( ch = is.read() ) != -1 ){

b.append( (char)ch );

}

dos.close();

return true;

} catch (Exception e) {

e.printStackTrace();

return false;

}

}


퍼미션 주고
<uses-permission android:name="android.permission.INTERNET"/>

이렇게 하면 끝!. 근데 실행은 제대로 되지만 LogCat을 보면 기분나쁜 로그가 많이 떠있다. ㅡㅡ;;; 여튼 아파치 서버로 파일 전송하기 완료!!!!
그리고 분홍색으로 되어진 부분은 각자의 실행 환경에 맞게 고치는 센스가 필요

===================================================================================================================


'6. With IT > 6.1 Android' 카테고리의 다른 글

안드로이드 종합  (0) 2013.02.18
이클립스 플러그인(svn)설치  (0) 2013.02.06
파일전송(ftp)  (1) 2013.02.01
구글 지도 띄우기  (1) 2013.01.28
sdcard안의 파일 내용 얻기  (0) 2012.02.01