Java将图片转为64位编码传到前台

 Java后台方法:

@RequestMapping(path = "/uploadImg", method = RequestMethod.POST)
	@ResponseBody
	public String uploadImg(@RequestParam("file") MultipartFile file, HttpServletRequest request,
            HttpServletResponse response) throws Exception{
	    StringBuffer ImgBase64=new StringBuffer();
	    if (file == null) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST);
            return "";
        }
        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        ImgBase64.append("data:image/");
        ImgBase64.append(suffix);
        ImgBase64.append(";base64,");
        InputStream fileInput = file.getInputStream();
        byte[] buffer=new byte[fileInput.available()];
        try {
            fileInput.read(buffer);
        } catch (Exception e) {
            throw new Exception("fileInput read to byte error!");
        }finally{
            fileInput.close();
        }
        BASE64Encoder base64Encoder = new BASE64Encoder();
        String Bese64Str=base64Encoder.encode(buffer);
        ImgBase64.append(Bese64Str);
        return ImgBase64.toString();
	}

 

你可能感兴趣的:(图片显示)