2011-12-28 5 views
10

스프링 웹 서비스를 사용하여 이미지를 보내는 동안 문제가 발생했습니다.스프링에서 웹 서비스에서 이미지를 보내는 방법

@Controller 
public class WebService { 

    @RequestMapping(value = "/image", headers = "Accept=image/jpeg, image/jpg, image/png, image/gif", method = RequestMethod.GET) 
    public @ResponseBody byte[] getImage() { 
     try { 
      InputStream inputStream = this.getClass().getResourceAsStream("myimage.jpg"); 
      BufferedImage bufferedImage = ImageIO.read(inputStream); 
      ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); 
      ImageIO.write(bufferedImage , "jpg", byteArrayOutputStream); 
      return byteArrayOutputStream.toByteArray(); 

     } catch (IOException e) { 
      throw new RuntimeException(e); 
     } 
    } 
} 

@ResponseBody 아래와 같이

I 작성한 JSON 제어기로 응답으로 변환한다.

웹 서비스를 테스트하기 위해 RestClient를 사용하고 있습니다.

하지만 내가 http://localhost:8080/my-war-name/rest/image URL로 타격을 가할 때.

Header 
Accept=image/jpg 

나는 실패 창-1252 인코딩을 사용하여 문자열을 위해 RESTClient

응답 본체의 변환에 다음과 같은 오류에 직면. 응답 본문이 설정되지 않았습니다! 내가 이

헤더가 너무 오류가 예상 추가되지 않습니다

 
HTTP Status 405 - Request method 'GET' not supported 

type Status report 

message Request method 'GET' not supported 

description The specified HTTP method is not allowed for the requested resource (Request method 'GET' not supported). 

는 또한

하면 오류 아래에 직면 (이 나를 인도 해주십시오) 브라우저 크롬과 파이어 폭스

을 사용하고

이 요청으로 식별 된 리소스는 특성이 허용되지 않는 응답을 생성하는 만 가능합니다. accordi 요청에 겨 나는 http://krams915.blogspot.com/2011/02/spring-3-rest-web-service-provider-and.html 자습서를 따랐다()

헤더를 "동의 함".

내 requirment는 Android 클라이언트로 이미지를 바이트 형식으로 전송하는 것입니다.

+0

[스프링 MVC : @ResponseBody의 이미지를 반환하는 방법] (http://stackoverflow.com/questions/5690228/spring-mvc-how-to-turnurn-image-in-responsebody) – skaffman

답변

1

json으로 변환을 변환하고 바이트 배열을있는 그대로 보냈습니다.

단점은 기본적으로 application/octet-stream 콘텐츠 형식을 보내는 것입니다.

스위트가 아닌 경우 등록 된 이미지 리더가 지원하는 이미지 유형을 보낼 수있는 BufferedImageHttpMessageConverter을 사용할 수 있습니다. 하면서

@RequestMapping(value = "/image", headers = "Accept=image/jpeg, image/jpg, image/png, image/gif", method = RequestMethod.GET) 
public @ResponseBody BufferedImage getImage() { 
    try { 
     InputStream inputStream = this.getClass().getResourceAsStream("myimage.jpg"); 
     return ImageIO.read(inputStream); 


    } catch (IOException e) { 
     throw new RuntimeException(e); 
    } 
} 

:

그런 다음 당신은 당신의 방법을 변경할 수 있습니다

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> 
    <property name="order" value="1"/> 
    <property name="messageConverters"> 
     <list> 
      <bean class="org.springframework.http.converter.BufferedImageHttpMessageConverter"/> 
     </list> 
    </property> 
</bean> 

당신의 스프링 설정에.

0

여기에 제가 작성한 방법이 있습니다.

이미지를 페이지에 인라인으로 표시하고 필요에 따라 클라이언트에 다운로드해야하므로 선택적 매개 변수를 사용하여 해당 헤더를 설정해야합니다.

Document은 문서를 나타내는 내 엔티티 모델입니다. 해당 파일을 저장하는 레코드의 ID 이름을 따라 이름이 지정된 디스크에 파일 자체가 저장되어 있습니다.원래 파일 이름과 MIME 유형은 Document 객체에 저장됩니다.

@RequestMapping("/document/{docId}") 
public void downloadFile(@PathVariable Integer docId, @RequestParam(value="inline", required=false) Boolean inline, HttpServletResponse resp) throws IOException { 

    Document doc = Document.findDocument(docId); 

    File outputFile = new File(Constants.UPLOAD_DIR + "/" + docId); 

    resp.reset(); 
    if (inline == null) { 
     resp.setHeader("Content-Disposition", "attachment; filename=\"" + doc.getFilename() + "\""); 
    } 
    resp.setContentType(doc.getContentType()); 
    resp.setContentLength((int)outputFile.length()); 

    BufferedInputStream in = new BufferedInputStream(new FileInputStream(outputFile)); 

    FileCopyUtils.copy(in, resp.getOutputStream()); 
    resp.flushBuffer(); 

} 
17

답 이외에 soulcheck. Spring은 을 생성하여 속성을 @RequestMapping annotation에 추가했습니다. 따라서 해결책은 더 쉽게 지금 : #soulcheck에 의해

@RequestMapping(value = "/image", method = RequestMethod.GET, produces = "image/jpg") 
public @ResponseBody byte[] getFile() { 
    try { 
     // Retrieve image from the classpath. 
     InputStream is = this.getClass().getResourceAsStream("/test.jpg"); 

     // Prepare buffered image. 
     BufferedImage img = ImageIO.read(is); 

     // Create a byte array output stream. 
     ByteArrayOutputStream bao = new ByteArrayOutputStream(); 

     // Write to output stream 
     ImageIO.write(img, "jpg", bao); 

     return bao.toByteArray(); 
    } catch (IOException e) { 
     logger.error(e); 
     throw new RuntimeException(e); 
    } 
} 
+0

감사합니다. . 그것은 효과가 있었다. – maverickosama92

3

대답은 부분적으로 권리입니다. 구성은 mvc-annotation 요소와 충돌하기 때문에 Spring의 최신 버전에서는 작동하지 않습니다. 아래의 구성을 시도하십시오.

<mvc:annotation-driven> 
    <mvc:message-converters register-defaults="true"> 
    <bean class="org.springframework.http.converter.BufferedImageHttpMessageConverter"/> 
    </mvc:message-converters> 
</mvc:annotation-driven> 

일단 설정 파일에 위의 구성이 있으면. 아래 코드는 작동합니다 :

@RequestMapping(value = "/image", headers = "Accept=image/jpeg, image/jpg, image/png, image/gif", method = RequestMethod.GET) 
public @ResponseBody BufferedImage getImage() { 
    try { 
     InputStream inputStream = this.getClass().getResourceAsStream("myimage.jpg"); 
     return ImageIO.read(inputStream); 
    } catch (IOException e) { 
     throw new RuntimeException(e); 
    } 
} 
1

this article on the excellent baeldung.com website을 참조하십시오.

당신은 당신의 봄 컨트롤러에서 다음 코드를 사용할 수 있습니다

@RequestMapping(value = "/rest/getImgAsBytes/{id}", method = RequestMethod.GET) 
public ResponseEntity<byte[]> getImgAsBytes(@PathVariable("id") final Long id, final HttpServletResponse response) { 
    HttpHeaders headers = new HttpHeaders(); 
    headers.setCacheControl(CacheControl.noCache().getHeaderValue()); 
    response.setContentType(MediaType.IMAGE_JPEG_VALUE); 

    try (InputStream in = imageService.getImageById(id);) { // Spring service call 
     if (in != null) { 
      byte[] media = IOUtils.toByteArray(in); 
      ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(media, headers, HttpStatus.OK); 
      return responseEntity; 
     } 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    return new ResponseEntity<>(null, headers, HttpStatus.NOT_FOUND); 
} 

주 : IOUtils는 공통 IO 아파치 라이브러리에서 제공됩니다. 나는 스프링 서비스를 사용하여 데이터베이스에서 img/pdf Blob을 검색하고있다.

콘텐츠 유형에 MediaType.APPLICATION_PDF_VALUE를 사용해야한다는 점을 제외하면 pdf 파일과 비슷한 처리 방법입니다.

<html> 
    <head> 
    </head> 
    <body> 
    <img src="https://localhost/rest/getImgDetectionAsBytes/img-id.jpg" /> 
    <br/> 
    <a href="https://localhost/rest/getPdfBatchAsBytes/pdf-id.pdf">Download pdf</a> 
    </body> 
</html> 

을 ... 또는 당신은 당신의 브라우저에서 직접 웹 서비스 메서드를 호출 할 수 있습니다 : 그리고 당신은 HTML 페이지에서 이미지 파일이나 PDF 파일을 참조 할 수 있습니다.

관련 문제