2010-04-15 3 views
3

멀티 파트 파일 업로드를 허용하는 웹 서버에 이미지를 업로드하는 프로그램을 만들려고합니다.자바에서 다중 파트 파일 업로드 게시 요청

더 구체적으로 "pic"변수로 파일을 보내는 http://iqs.me에 http POST 요청을 보내려고합니다.

많은 시도를 해봤지만 가까운지 알 수 없습니다. 가장 어려운 부분은 HttpURLConnection을 사용하여 POST 유형을 요청하는 것입니다. 내가 얻는 반응은 GET을 만드는 것처럼 보입니다.

(그리고 내가 제 3 자 libs가없이이 작업을 수행 할 수)

업데이트 : 비 작동 코드가 여기에 표시됩니다 (오류없이하지만 POST를 수행하지 않는 것) :

HttpURLConnection conn = null; 
    BufferedReader br = null; 
    DataOutputStream dos = null; 
    DataInputStream inStream = null; 

    InputStream is = null; 
    OutputStream os = null; 
    boolean ret = false; 
    String StrMessage = ""; 
    String exsistingFileName = "myScreenShot.png"; 

    String lineEnd = "\r\n"; 
    String twoHyphens = "--"; 
    String boundary = "*****"; 

    int bytesRead, bytesAvailable, bufferSize; 
    byte[] buffer; 
    int maxBufferSize = 1*1024*1024; 
    String responseFromServer = ""; 
    String urlString = "http://iqs.local.com/index.php"; 


    try{ 
    FileInputStream fileInputStream = new FileInputStream(new File(exsistingFileName)); 
    URL url = new URL(urlString); 
    conn = (HttpURLConnection) url.openConnection(); 
    conn.setDoInput(true); 
    conn.setDoOutput(true); 
    conn.setRequestMethod("POST"); 
    conn.setUseCaches(false); 

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

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

    dos.writeBytes(twoHyphens + boundary + lineEnd); 
    dos.writeBytes("Content-Disposition: form-data; name=\"pic\";" + " filename=\"" + exsistingFileName +"\"" + lineEnd); 
    dos.writeBytes(lineEnd); 

    bytesAvailable = fileInputStream.available(); 
    bufferSize = Math.min(bytesAvailable, maxBufferSize); 
    buffer = new byte[bufferSize]; 

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

    while (bytesRead > 0){ 
     dos.write(buffer, 0, bufferSize); 
     bytesAvailable = fileInputStream.available(); 
     bufferSize = Math.min(bytesAvailable, maxBufferSize); 
     bytesRead = fileInputStream.read(buffer, 0, bufferSize); 
    } 

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

    fileInputStream.close(); 
    dos.flush(); 
    dos.close(); 


    }catch (MalformedURLException ex){ 
    System.out.println("Error:"+ex); 
    }catch (IOException ioe){ 
    System.out.println("Error:"+ioe); 
    } 

    try{ 
    inStream = new DataInputStream (conn.getInputStream()); 
    String str; 
    while ((str = inStream.readLine()) != null){ 
     System.out.println(str); 
    } 
    inStream.close(); 
    }catch (IOException ioex){ 
    System.out.println("Error: "+ioex); 
    } 
+0

을 업로드이 사용하고 발견 ... –

+0

좋아 코드 : – Martin

+0

그렇게하지를 추가 지금 당장이 모든 것을 처리 할 시간이 있지만 작업 코드 샘플로 답변을 게시 한 후에도 유용 할 수 있습니다. [here] (http://stackoverflow.com/questions/2469451/upload- 파일 -와 - 자바/2469587 # 2469587)와 후속 [여기] (http://stackoverflow.com/questions/2477449/simple-stream-read-write-question-in-java/2478127#2478127). 모든 자세한 정보를 유지하고 모든 작업을 쉽게하려면 [Apache HttpComponents HttpClient] (http://hc.apache.org/httpcomponents-client/index.html)를 진행하는 것이 좋습니다. – BalusC

답변

2

두 가지 :

  1. call setRequestMethod to set the HTTP request to be a POST을 확인하십시오. 수작업으로 멀티 파트 POST 요청을하는 것은 어렵고 오류가 발생하기 쉽다는 것을 경고해야합니다.

  2. * NIX에서 실행중인 경우 netcat 도구는이 항목을 디버깅하는 데 매우 유용합니다. 실행
    netcat -l -p 3000

    및 프로그램을 포트 3000으로 지정하십시오. 프로그램이 무엇을 보내고 있는지 정확히 알 수 있습니다 (나중에 Control-C를 눌러 닫습니다).

+0

"POST"로 설정했습니다. * NIX는 현재 실행 중이지만 좋은 팁은 다른 시간을 사용합니다. – Martin

+2

'setDoOutput (true)'는 이미 그것을 암시 적으로 설정하여 게시합니다. – BalusC

0

내가 그렇지 않으면 우리는 거의 당신을 도울 수, 그것은 다중 파일에 유용한 코드를 게시하시기 바랍니다

File f = new File(filePath); 
PostMethod filePost = new PostMethod(url); 
Part[] parts = { new FilePart("file", f) }; 
filePost.setRequestEntity(new MultipartRequestEntity(parts, 
filePost.getParams())); 
HttpClient client = new HttpClient(); 
status = client.executeMethod(filePost); 
+1

이 코드는 apache commons httpclient에 따라 다릅니다. – rmuller