2008-09-03 9 views
4

서블릿을 사용하는 Java 코드와 Apache Commons FileUpload를 사용하여 파일을 설정된 디렉토리에 업로드했습니다. 문자 데이터 (예 : 텍스트 파일)는 정상적으로 작동하지만 이미지 파일이 왜곡되어 표시됩니다. 나는 그들을 열 수 있지만 이미지가 보이지 않아야한다. 여기에 내 코드입니다 :왜 이미지가 왜곡되어 나오지 않습니까?

서블릿은

protected void doPost(HttpServletRequest request, HttpServletResponse response) 
    throws ServletException, IOException { 
    try { 
     String customerPath = "\\leetest\\"; 

     // Check that we have a file upload request 
     boolean isMultipart = ServletFileUpload.isMultipartContent(request); 

     if (isMultipart) { 
     // Create a new file upload handler 
     ServletFileUpload upload = new ServletFileUpload(); 

     // Parse the request 
     FileItemIterator iter = upload.getItemIterator(request); 
     while (iter.hasNext()) { 
      FileItemStream item = iter.next(); 
      String name = item.getFieldName(); 
      if (item.isFormField()) { 
      // Form field. Ignore for now 
      } else { 
      BufferedInputStream stream = new BufferedInputStream(item 
       .openStream()); 
      if (stream == null) { 
       LOGGER 
        .error("Something went wrong with fetching the stream for field " 
         + name); 
      } 

      byte[] bytes = StreamUtils.getBytes(stream); 
      FileManager.createFile(customerPath, item.getName(), bytes); 

      stream.close(); 
      } 
     } 
     } 
    } catch (Exception e) { 
     throw new UploadException("An error occured during upload: " 
      + e.getMessage()); 
    } 
} 

StreamUtils.getBytes (스트림)과 같이 보인다 :

public static byte[] getBytes(InputStream src, int buffsize) 
     throws IOException { 
    ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); 
    byte[] buff = new byte[buffsize]; 
    while (true) { 
     int nBytesRead = src.read(buff); 
     if (nBytesRead < 0) { 
     break; 
     } 
     byteStream.write(buff); 
    } 

    byte[] result = byteStream.toByteArray(); 
    byteStream.close(); 

    return result; 
} 

그리고 마지막으로 FileManager.createFile은 다음과 같습니다

public static void createFile(String customerPath, String filename, 
     byte[] fileData) throws IOException { 
    customerPath = getFullPath(customerPath + filename); 
    File newFile = new File(customerPath); 
    if (!newFile.getParentFile().exists()) { 
     newFile.getParentFile().mkdirs(); 
    } 

    FileOutputStream outputStream = new FileOutputStream(newFile); 
    outputStream.write(fileData); 
    outputStream.close(); 
    } 

수있는 사람의 자리 내가 뭘 잘못하고있어?

건배, 리

답변

4

한 가지 StreamUtils.getBytes()에서이 블록에서 여기에 있습니다 :. 라인 6에서

1 while (true) { 
2 int nBytesRead = src.read(buff); 
3 if (nBytesRead < 0) { 
4  break; 
5 } 
6 byteStream.write(buff); 
7 } 

, 그것은 상관없이 읽을 바이트 수를, 전체 버퍼를 기록하지 I 이것이 항상 사실이 될 것이라고 확신하지는 않습니다. 그것은이 같은 더 정확한 것 :

1 while (true) { 
2 int nBytesRead = src.read(buff); 
3 if (nBytesRead < 0) { 
4  break; 
5 } else { 
6  byteStream.write(buff, 0, nBytesRead); 
7 } 
8 } 

주 라인에 두 개의 추가 매개 변수와 함께, 5 행에 '다른 사람'(배열 인덱스 시작 위치 및 복사 할 길이) 6.

내가 할 수있는 Image와 같은 큰 파일의 경우, 버퍼는 채워지기 전에 반환됩니다 (어쩌면 더 기다리고있을 수도 있음). 즉, 의도하지 않게 버퍼의 끝 부분에 남아있는 오래된 데이터를 쓰게됩니다. EoF에서 거의 대부분의 경우 버퍼가 1 바이트 이상으로 추정되지만 EoF의 추가 데이터가 손상의 원인이 아닐 수 있습니다 ... 바람직하지 않습니다.

0

하여 이미지 왜곡을 통해 또는 당신이가는 길에 몇 가지 패킷을 삭제되지 않습니다 오지 않을 것을 확신합니다.

0

내가 모르는 어떤 차이를 하지만, 메소드 서명의 불일치가있는 것 같습니다.

byte[] bytes = StreamUtils.getBytes(stream); 

이 포함 된 방법 소스는 두 개의 인수를 가지고있는 동안 : 당신의 doPost() 방법으로 불리는 getBytes() 방법은 단 하나의 인수를 가지고하는 데 도움이

public static byte[] getBytes(InputStream src, int buffsize) 

희망을.

0

원본 파일과 업로드 된 파일에 체크섬을 수행하고 즉각적인 차이점이 있는지 확인할 수 있습니까?

diff가 있는지 살펴보면 변경되지 않은 파일의 정확한 부분을 확인할 수 있습니다.

마음에 떠오르는 것은 스트림의 시작이나 끝, 또는 엔디안입니다. 내가 좋아하지 않는

1

나는 단지 commons io을 사용합니다. 그러면 IOUtils를 할 수 있습니다.복사 (InputStream, OutputStream);

다른 유용한 유틸리티 메소드가 많이 있습니다.

관련 문제