简体   繁体   English

在Rest API中发送图像文件数据

[英]Sending Image File data in Rest API

To a Spring Rest API, I am trying to send a image data in Base 64 encoded String in Request Body - which I will decode and store as an Image file in Server's file System using below method. 对于Spring Rest API,我试图在请求正文中以Base 64编码的字符串发送图像数据-我将使用以下方法将其解码并作为图像文件存储在服务器的文件系统中。

public static BufferedImage decodeToImage(String image) {

        BufferedImage image = null;
        byte[] imageByte;
        try {
            BASE64Decoder decoder = new BASE64Decoder();
            imageByte = decoder.decodeBuffer(image);
            ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
            image = ImageIO.read(bis);
            bis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return image;
    }

Encoding Method, 编码方式

public static String encodeToString(BufferedImage image, String type) {
        String imageString = null;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        try {
            ImageIO.write(image, type, bos);
            byte[] imageBytes = bos.toByteArray();

            BASE64Encoder encoder = new BASE64Encoder();
            imageString = encoder.encode(imageBytes);

            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return imageString;
    }

However, For a Image file of 100 kb size - The length of Base 64 encoded String is 1 million Characters Approx. 但是,对于100 kb大小的图像文件-Base 64编码的字符串的长度约为1百万个字符。 This Big size data is not feasible to be sent in rest API request body. 在休息API请求正文中发送此大数据是不可行的。

Is there a better way to send Image data / upload Image to server using Rest Web Services?? 是否有更好的方法使用Rest Web Services发送图像数据/将图像上传到服务器?

Thanks for the suggestions, I am handling this using MultiPart File. 感谢您的建议,我正在使用MultiPart File处理它。

@RequestMapping(value="/uploadImage", method=RequestMethod.POST)
    public @ResponseBody String imageUpload( 
            @RequestParam("imageFile") MultipartFile file){
         //upload file using byte date from file
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM