您的位置:首页 > 其它

Base64相关

2017-10-20 00:00 10 查看
在工程springboot-ueditor中有测试:

链接:https://github.com/wtkid/workspace_G/tree/master/ideaprojects/spirngboot-ueditor

Base64图片保存是以String的形式存储的,页面上img标签显示图片的方式:

①src直接填写这个字符串是可以显示的,

②src填写的如果是一个url,并且这个url是以流的方式输出的图片。

那如果url不是以流的形式输出的,而是返回base64的一串string,name直接填这个url能否显示图片呢,答案是不能,所以我们需要将这个String转换成流的方式输出,以下是转流的工具类。

注意:spring自己也有一套org.springframework.util.Base64Utils也可以用。



以下是方法:



我自己的Base64utils.

package com.wt.ueditor.utils;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.*;

/**
* @Description
* @Author: wangtao
* @Date:12:09 2017/10/20
* @Email:tao8.wang@changhong.com
*/
public class Base64Utils {

public static String encode(InputStream is) throws IOException {
BASE64Encoder encoder = new BASE64Encoder();
byte[] data = new byte[is.available()];
is.read(data);
is.close();
String str = encoder.encode(data);
return str;
}

public static InputStream decode(String file) throws Exception {
BASE64Decoder decoder = new BASE64Decoder();
byte[] bytes = decoder.decodeBuffer(file);
//测试时发现不调整异常数据也正确,为了避免以后出错,加上这一段
for (int i = 0; i < bytes.length; ++i) {
if (bytes[i] < 0) {// 调整异常数据
bytes[i] += 256;
}
}
InputStream in = new ByteArrayInputStream(bytes);
return in;
}

public static void toOutputStream(String file, OutputStream os) {
try {
InputStream in = decode(file);
inputStreamToOutputStream(in, os);
} catch (Exception e) {
e.printStackTrace();
}
}

public static void inputStreamToOutputStream(InputStream in, OutputStream os) throws IOException {
byte[] b = new byte[4096];
Integer len = -1;
while ((len = in.read(b)) != -1) {
os.write(b, 0, len);
}
os.flush();
in.close();
os.close();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息