2014-07-21 2 views
6

Java Desktop Env에서 NanoHTTPD webserver 2.1.0을 사용하고 있습니다. (어떤 안드로이드 없음)NanoHTTPD : html 양식 (POST)을 사용하여 파일 업로드

모든 것이 잘 작동 ...하지만 파일 업로드 (PUT 양식 지원되지 않습니다) 여기

내 HTML 코드 POST 메서드를 사용하고 있습니다 :

<form method="post" enctype="multipart/form-data"> 
    choose a file<br> 
    <input name="file" type="file" size="50" maxlength="100000""> 
    <button type="submit">upload</button> 
</form> 

그리고 여기

public Response serve(IHTTPSession session) { 
    if (session.getMethod() == Method.POST) { 
     Map<String, String> files = new HashMap<String, String>(); 
     session.parseBody(files); 
     //this prints {file=C:\path-to-java-tmp-files\NanoHTTPD-4635244586997909485} 
     //the number is always different 
     System.out.println(files.toString()); 
    } else { 
     //page containing the index.html including the form 
     return page; 
    } 
} 

그리고

이 문제입니다 : 가 임시 파일이 존재하지 않습니다 여기 내 서버 메도이다. 끝에 다른 "숫자"가있는 또 다른 임시 파일이 있는데이 파일은 내용이 업로드 된 파일의 내용과 동일하기 때문에 올바른 파일 인 것 같습니다. 어떻게 올바른 임시 파일 이름을 얻는가?

또 다른 문제는 다음 내용이 그림 또는 바이너리 경우

-----------------------------115801144322347 
Content-Disposition: form-data; name="file"; filename="filename.txt" 
Content-Type: application/octet-stream 

-->content of the uploaded file 


-----------------------------115801144322347-- 

이 문제입니다 : 임시 파일은 구멍 POST의 콘텐츠가 포함되어 있습니다.

NanoHTTPD는 POST 요청으로 어떤 spezial도하지 않는 것 같습니다. 그것은 항상 동일합니다 ... 요청을 tmp 파일에 저장하고 페이지를 제공합니다. So : - 올바른 임시 파일을 얻는 방법? -> 나는 이것이 버그라고 생각한다. 나는 정확한 경로와 이름을 얻고 있지만 "숫자"는 깨졌습니다. idk ... 업로드가 발생하면 임시로 java tmp-path를 변경하고 파일을 항상 삭제해야합니다. 그렇다면 하나의 tmp 파일 만이 어떤 이름과도 독립적입니까? - 파일에서 html 요청 헤더를 삭제하는 방법

아니면 뭔가 잘못하고있는 거예요? 이것은 nanohttpd에 파일을 업로드하는 올바른 방법입니까?

당신의 도움을 위해!

+0

나는 7 월에 게시했지만 해결책을 찾았습니까? NanoHttpd가 이진 파일에 대해서도 readLine()을 사용하기 때문에 손상된 PNG 파일이 생성됩니다. – twig

+0

아니요. 나는 해결책을 찾지 못했다. (나는 방금 포기했다. – user3796786

답변

3

"게시자가 수정 사항을 찾았습니까?" 질문을했지만 오늘 답장 할 때까지 게시하는 것을 잊어 버렸습니다.

<form method="post" enctype="multipart/form-data" action="http://whatever.com/path/"> 
    <input type="file" name="file" /> 
    <input type="hidden" name="extra_data" value='blah blah blah' /> 
    <input type="submit" value="Send" /> 
</form> 

그리고 자바 코드 :

if (session.getMethod() == Method.POST) { 
    try { session.parseBody(files); } 
    catch (IOException e1) { e1.printStackTrace(); } 
    catch (ResponseException e1) { e1.printStackTrace(); } 

    extraData = session.getParms().get("extra_data"); 
    File file = new File(files.get("file")); 
} 

중요한 것은 당신이 보내는 데이터는 파일 데이터, 파일 이름과 파일의 MIME 타입와 함께 제공됩니다.

제 경우에는 파이썬 요청을 POST에 사용하고 충분한 데이터를 보내지 않았습니다. 올바른 포스트 구조는 다음과 같습니다

file_data = { 'file': ('test.png', open('../some_file.png', 'rb'), 'image/png') } 
requests.post("http://whatever.com/path", data = { 'extra_data': "blah blah blah" }, files = file_data) 

위의 코드는 "some_file.png"에서 읽지 만은 "test.png"라고 서버를 알려줍니다.

희망 하시겠습니까?