Sending Multiple images from web service SPRINGBOOT+REST+MAVEN

流过昼夜 提交于 2021-02-07 09:41:53

问题


I am writing a web service in spring boot restful web App using which i am sending a image to anyone who wants to consume it below is a code snippet which worked for me

@RequestMapping(value = "/photo_1",method = RequestMethod.GET )  
public ResponseEntity<byte[]> greeting_image_1(@RequestParam(value="name", defaultValue="World") String name) throws IOException{
    InputStream in = getClass().getResourceAsStream("/images/someimage.jpg");       
    byte[] a = IOUtils.toByteArray(in);
    final HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.IMAGE_JPEG); 
    return new ResponseEntity<byte[]>(a,headers,HttpStatus.CREATED);            
}

This web service works perfectly fine in case i want to return a single image from a web service

But what if in case i want to return array of images(i.e. more than 1 image)

Any help is highly appreciated.

Regards,


回答1:


Here's the sample code that I wrote to generate a multipart response with multiple images in it. It's properly consumed by Firefox and it prompts to save each image in the response.

public ResponseEntity<byte[]> showImages () throws IOException {
    String boundary="---------THIS_IS_THE_BOUNDARY";
    List<String> imageNames = Arrays.asList(new String[]{"1.jpg","2.jpg"});
    List<String> contentTypes = Arrays.asList(new String[]{MediaType.IMAGE_JPEG_VALUE,MediaType.IMAGE_JPEG_VALUE});
    List<Byte[]> imagesData = new ArrayList<Byte[]>();
    imagesData.add(ArrayUtils.toObject(IOUtils.toByteArray(getClass().getResourceAsStream("/images/1.jpg"))));
    imagesData.add(ArrayUtils.toObject(IOUtils.toByteArray(getClass().getResourceAsStream("/images/2.jpg"))));
    byte[] allImages = getMultipleImageResponse(boundary, imageNames,contentTypes, imagesData);
    final HttpHeaders headers = new HttpHeaders();
    headers.set("Content-Type","multipart/x-mixed-replace; boundary=" + boundary);
    return new ResponseEntity<byte[]>(allImages,headers,HttpStatus.CREATED);
}

private static byte[] getMultipleImageResponse(String boundary, List<String> imageNames, List<String> contentTypes, List<Byte[]> imagesData){
    byte[] finalByteArray = new byte[0];
    Integer imagesCounter = -1;
    for(String imageName : imageNames){
        imagesCounter++;
        String header="--" + boundary 
                + "\r\nContent-Disposition: form-data; name=\"" + imageName
                + "\"; filename=\"" + imageName + "\"\r\n"
                + "Content-type: " + contentTypes.get(imagesCounter) + "\r\n\r\n";
        byte[] currentImageByteArray=ArrayUtils.addAll(header.getBytes(), ArrayUtils.toPrimitive(imagesData.get(imagesCounter)));
        finalByteArray = ArrayUtils.addAll(finalByteArray,ArrayUtils.addAll(currentImageByteArray, "\r\n\r\n".getBytes()));
        if (imagesCounter == imageNames.size() - 1) {
            String end = "--" + boundary + "--";
            finalByteArray = ArrayUtils.addAll(finalByteArray, end.getBytes());
        }
    }
    return finalByteArray;
}

You should implement this depending on the capability of the consumer. If the consumer can parse multipart response, please go ahead with this approach, else consider other options like

  1. Sending a zipped file of all images
  2. Returning a json/xml of image names along with URLs to download them
  3. Returning a json/xml with all images in Base64 encoded string

You may also send a html response with all images embedded in it using the below code. This should work fine in all browsers as it is pure html.

public ResponseEntity<byte[]> getAllImages() throws IOException {
    List<String> imageNames = Arrays.asList(new String[]{"1.jpg","2.jpg"});
    List<String> contentTypes = Arrays.asList(new String[]{MediaType.IMAGE_JPEG_VALUE,MediaType.IMAGE_JPEG_VALUE});
    List<Byte[]> imagesData = new ArrayList<Byte[]>();
    imagesData.add(ArrayUtils.toObject(IOUtils.toByteArray(getClass().getResourceAsStream("/images/1.jpg"))));
    imagesData.add(ArrayUtils.toObject(IOUtils.toByteArray(getClass().getResourceAsStream("/images/2.jpg"))));
    byte[] htmlData=getHtmlData(imageNames,contentTypes, imagesData);
    final HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.TEXT_HTML);
    return new ResponseEntity<byte[]>(htmlData,headers,HttpStatus.OK);
}

private static byte[] getHtmlData(List<String> imageNames, List<String> contentTypes, List<Byte[]> imagesData){
    String htmlContent="<!DOCTYPE html><html><head><title>Images</title></head><body>";
     Integer imagesCounter = -1;
    for(String imageName : imageNames){
         imagesCounter++;
        htmlContent = htmlContent + "<br/><br/><b>" + imageName + "</b><br/></br/><img src='data:" + contentTypes.get(imagesCounter) + ";base64, " + org.apache.commons.codec.binary.StringUtils.newStringUtf8(Base64
                .encodeBase64(ArrayUtils.toPrimitive(imagesData.get(imagesCounter)))) + "'/>";
    }
    htmlContent = htmlContent + "</body></html>";
    return htmlContent.getBytes();
}



回答2:


You should take a look to "Uploading Files" Spring Boot guide : https://spring.io/guides/gs/uploading-files/

There's a an example of upload and download.



来源:https://stackoverflow.com/questions/38352053/sending-multiple-images-from-web-service-springbootrestmaven

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!