2012-01-06 2 views
1

Apache commons 파일 업로드 라이브러리를 사용하여 파일 업로드를 처리하는 서블릿을 작성했습니다.서블릿이 다중 요청에서 FileItem을 찾지 못하는 이유는 무엇입니까?

protected void doPost(HttpServletRequest request, HttpServletResponse response) 
     throws ServletException, IOException { 
    boolean isMultipart = ServletFileUpload.isMultipartContent(request); 

    if (isMultipart) { 
     try { 
      DiskFileItemFactory fileItemFactory = new DiskFileItemFactory(); 

      // Set size threshold for storing upload 
      fileItemFactory.setSizeThreshold(1 * 1024 * 50); // 50 KB 

      // Set temporary directory to store uploaded files above threshold size 
      fileItemFactory.setRepository(new File(TEMP_DIRECTORY)); 

      ServletFileUpload upload = new ServletFileUpload(fileItemFactory); 

      //HashMap<String, String> params = new HashMap<String, String>(); 


      FileItemIterator iterator = upload.getItemIterator(request); 
      upload.setSizeMax(REQUEST_MAX_SIZE); 

      List items = upload.parseRequest(request); 
      Iterator it = items.iterator(); 

      while (it.hasNext()) { 
       FileItem item = (FileItem) it.next(); 

       if(item.isFormField()) { 

       } else { 
        String contentType = item.getContentType(); 
        String fileName = item.getName(); 
        String fieldName = item.getFieldName(); 
        boolean isInMemory = item.isInMemory(); 
        long sizeInBytes = item.getSize(); 
        File uploadedFile = new File(PATH + "new_audio1.amr"); 

        item.write(uploadedFile); 

        System.out.println("Field: " + fieldName); 
        System.out.println("File name: " + fileName); 
        System.out.println("Size: " + sizeInBytes); 
        System.out.println("Is in memory:" + isInMemory); 
       } 
      } 

     } catch (Exception ex) { 
      throw new ServletException(ex); 
     } 
    } else { 
     throw new ServletException(); 
    } 

나에게 목록 '항목을'탈출 그래서 업로드 된 파일을 잡을 수없는 비어있는 몇 가지 이유를 들어 다음 코드의 일부이다. 업로드 자체를 들어

, 나는 몇 가지 자바 코드를 작성했습니다 : 파일이 첨부 제대로 업로드되는 것처럼

File audioFile = new File("C:\\Users\\Soto\\Desktop\\test recording.amr"); 

    String url = "http://localhost:8080/AudioFileUpload/UploadServlet"; 
    String charset = "UTF-8"; 

    // random values 
    String latitude = "145"; 
    String longitude = "132"; 
    String speed = "0"; 


    String query; 
    try { 
     query = String.format("latitude=%s&longitude=%s&speed=%s", URLEncoder.encode(latitude, charset), URLEncoder.encode(longitude, charset), URLEncoder.encode(speed, charset)); 
    } catch (UnsupportedEncodingException e) { 
     query = String.format("latitude=%s&longitude=%s&speed=%s", latitude, longitude, speed); 
    } 

    HttpClient httpClient = new DefaultHttpClient(); 
    httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); 

    HttpPost httpPost = new HttpPost(url + "?" + query); 

    MultipartEntity mpEntity = new MultipartEntity(); 
    ContentBody cbFile = new FileBody(audioFile, "audio/AMR"); 
    mpEntity.addPart("audioFile", cbFile); 

    httpPost.setEntity(mpEntity); 

    HttpResponse response = null; 
    try { 
     response = httpClient.execute(httpPost); 
     HttpEntity responseEntity = response.getEntity(); 
     System.out.println(response.getStatusLine()); 

     if(responseEntity != null) 
      System.out.println(EntityUtils.toString(responseEntity)); 

     if(responseEntity != null) { 
      EntityUtils.consume(responseEntity); 
     } 

     httpClient.getConnectionManager().shutdown(); 

    } catch (ClientProtocolException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

그것은 나에게 느낀다. 또한 multipart/form-data 게시 요청으로 HTML을 통해 작업을 시도했지만 여전히 파일을 찾을 수 없습니다.

내가 뭘 잘못하고 있니?

편집

: 가 나는 경우 성명과 함께의 doPost()의 시작 부분에 라인을 제거 :

ServletFileUpload.isMultipartContent(request); 

그리고 업로드가 제대로 작동했다. 이 메소드가 요청의 '입력/출력/무엇이든지간에'스트림을 소비 할 수 있습니까?

감사합니다.

+0

브라우저에서 업로드를 시도 했습니까? –

답변

1

편집을 피들러를 사용하여 난의 doPost (의 시작 부분에 라인을 제거) if 문와 함께 :

ServletFileUpload.isMultipartContent(request); 

업로드가 올바르게 수행되었습니다. 이 메소드가 요청의 '입력/출력/무엇이든지간에'스트림을 소비 할 수 있습니까?

이것은 이상합니다. 모든 메소드는 요청 메소드가 POST과 같고 Content-Type 헤더가 multipart/으로 시작하는지 검사합니다. 당신이 볼

public static final boolean isMultipartContent(
     HttpServletRequest request) { 
    if (!"post".equals(request.getMethod().toLowerCase())) { 
     return false; 
    } 
    String contentType = request.getContentType(); 
    if (contentType == null) { 
     return false; 
    } 
    if (contentType.toLowerCase().startsWith(MULTIPART)) { 
     return true; 
    } 
    return false; 
} 

, 충격 아무것도 : 여기에 (년에 걸쳐 많이 변경되지 않은) 현재 최신 커먼즈는 FileUpload의 API 버전의 소스의 추출물이다.

request.getMethod() 또는 getContentType()을 호출 할 때 요청 본문이 암시 적으로 사용되는 버그를 나타내는 매우 모호하거나 버그가 많은 서블릿 컨테이너를 사용하고있는 것일 수 있습니다.

+0

Tomcat을 사용하고 있습니다. 나는 라인을 다시 추가하고 그것을 작동합니다. 나는이 프로젝트가 업데이트되지 않았다고 생각하여 3 시간 후에 모든 것이 잘되었다. 고맙다. –

0

콘텐츠 유형을 설정하는 것을 잊었을 까 요? 당신이 MultiPartPostData를 사용

왜 해달라고 와이어에 gking 뭐죠 볼

http://hc.apache.org/httpclient-3.x/apidocs/org/apache/commons/httpclient/methods/MultipartPostMethod.html

+1

해당 클래스는 더 이상 사용되지 않습니다. 그러나 그 도서관에 대한 링크가 있습니까? 편집 : 신경 쓰지 마, 그 도서관 전체가위원회에서 지금 내가 사용하고있는 도서관으로 대체되었습니다. –

관련 문제