如何使用spring将编码的base64图像上传到服务器

sri*_*ari 9 spring

我正在使用spring编写一个Web服务.
此服务将base64编码的图像作为String参数.
我想将此String解码为图像并上传到服务器.

@RequestMapping(value="/uploadImage",method = RequestMethod.POST)
public @ResponseBody String uploadImage(@RequestParam("encodedImage") String encodedImage)
{
    byte[] imageByte= Base64.decodeBase64(encodedImage);
    return null;
}
Run Code Online (Sandbox Code Playgroud)

sri*_*ari 11

下面的代码用于解码使用base 64编码的字符串并用于将图像上传到服务器。

这对我来说很好用..

@RequestMapping(value="/uploadImage2",method = RequestMethod.POST)
    public @ResponseBody String uploadImage2(@RequestParam("imageValue") String imageValue,HttpServletRequest request)
    {
        try
        {
            //This will decode the String which is encoded by using Base64 class
            byte[] imageByte=Base64.decodeBase64(imageValue);

            String directory=servletContext.getRealPath("/")+"images/sample.jpg";

            new FileOutputStream(directory).write(imageByte);
            return "success ";
        }
        catch(Exception e)
        {
            return "error = "+e;
        }

    }
Run Code Online (Sandbox Code Playgroud)

  • 我不得不在第一个逗号处拆分 imageValue 并取其余部分,因为我发送了包括“标题”在内的整个图像。此外,如果您使用 java.util.Base64,它是 Base64.getDecoder().decode()。希望这两个花絮对某人有所帮助。 (7认同)