springboot中涉及到的图片上传的问题以及富文本传输相关问题
一、上传图片
在图片上传中,将图片上传至服务器,并在数据库表中保存上传的图片的相关信息
upimage.sql
-- ----------------------------
-- Table structure for tbbupimage
-- ----------------------------
DROP TABLE IF EXISTS "public"."tbbupimage";
CREATE TABLE "public"."tbbupimage" (
"id" uuid NOT NULL,
"newsid" uuid,
"imagename" varchar(255) COLLATE "pg_catalog"."default",
"type" varchar(255) COLLATE "pg_catalog"."default",
"localurl" varchar(255) COLLATE "pg_catalog"."default",
"networkurl" varchar(255) COLLATE "pg_catalog"."default",
"createtime" timestamp(6),
"projectid" uuid,
"companionid" uuid,
"status" int4
)
;
COMMENT ON COLUMN "public"."tbbupimage"."id" IS 'id';
COMMENT ON COLUMN "public"."tbbupimage"."newsid" IS '新闻id';
COMMENT ON COLUMN "public"."tbbupimage"."imagename" IS '图片的名称';
COMMENT ON COLUMN "public"."tbbupimage"."type" IS '图片类型';
COMMENT ON COLUMN "public"."tbbupimage"."localurl" IS '本地磁盘访问路径';
COMMENT ON COLUMN "public"."tbbupimage"."networkurl" IS '网络访问路径';
COMMENT ON COLUMN "public"."tbbupimage"."createtime" IS '创建时间';
COMMENT ON COLUMN "public"."tbbupimage"."projectid" IS '项目id';
COMMENT ON COLUMN "public"."tbbupimage"."companionid" IS '合作伙伴id';
COMMENT ON COLUMN "public"."tbbupimage"."status" IS '状态:0有关联1无关联';
-- ----------------------------
-- Primary Key structure for table tbbupimage
-- ----------------------------
ALTER TABLE "public"."tbbupimage" ADD CONSTRAINT "tbbupimage_pkey" PRIMARY KEY ("id");
这里面的项目id,合作伙伴id,新闻id是该图片所关联的东西。status表示是否有关联(在删除数据时根据这个查询出所有无关联的数据同时删除本地资源),我在业务逻辑中是这样实现的(以项目id为例):
1、当添加项目时,需要上传图片,调用后端接口,上传成功后,返回给前端相应的数据(对应的一条数据库数据,里面有networkurl等)。此时的图片的projectid我传的null,status=1(表示无关联)
2、前端提交数据时将这个networkurl传给我,然后我再根据这个networkurl(由于文件名根据uuid生成,具有唯一性,所有networkurl也具有唯一性)修改指定图片的projectid,status=0(表示有关联)
上传图片逻辑实现:
@Value("${uploadImage.types}")
private String[] uploadImageTypes;//图片类型数组
@Value("${uploadImage.size}")
private int uploadImageSize;//图片大小
@Value("${uploadImage.serverUrl}")
private String uploadImageServerUrl;//上传到指定服务器
@Value("${uploadImage.baseUrl}")
private String uploadImageBaseUrl;//上传到服务器的指定路径
@Autowired
private UpImageDao upImageDao;
@Override
public ResultData uploadImage(MultipartFile multipartFile) {
String type = checkImage(multipartFile);
//上传的文件名及后缀
String fileName = multipartFile.getOriginalFilename();//文件名
String suffixName = fileName.substring(fileName.lastIndexOf("."));//后缀名
//当前日期的年月
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM");
String format = simpleDateFormat.format(new Date());
//重命名文件名
fileName = UUID.randomUUID() + suffixName;
//获取当前工程在本地磁盘的路径
String projectDir = System.getProperty("user.dir");//D:\workspace\clone\slkj
//本地存储位置:当前工程所在的目录+指定的目录+年月目录
String localUrl = projectDir + uploadImageBaseUrl + format.split("/")[0] + "\\" + format.split("/")[1] + "\\" + fileName;
logger.info("本地存储位置:" + localUrl);
File dest = new File(localUrl);
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
try {
multipartFile.transferTo(dest);
//外部请求图片的url
String networkUrl = uploadImageServerUrl + "/slkj/upimages/" + format + "/" + fileName;
logger.info("外部请求URL:" + networkUrl);
UpImageDO upImageDO = new UpImageDO(UUID.randomUUID().toString(), null, null,null, UpImageConstant.NO_LINK, fileName, type, localUrl, networkUrl, new Date());
upImageDao.insert(upImageDO);
return ResultDataUtils.success("上传成功", upImageDO);
} catch (IOException e) {
return ResultDataUtils.fail("上传失败");
}
}
/**
* 检查图片文件
*
* @param multipartFile
* @return fileType
*/
private String checkImage(MultipartFile multipartFile) {
if (multipartFile.isEmpty()) {
throw new BDException("请选择图片");
}
//检查格式
String fileType = multipartFile.getContentType();
logger.info("文件类型:" + fileType);
boolean flag = false;
for (String type : uploadImageTypes) {
if (fileType.equals(type)) {
flag = true;
break;
}
}
if (!flag) {
throw new BDException("请选择 png、jpg、jpeg、gif 格式的图片");
}
//检查文件大小
double imageSize = (double) multipartFile.getSize() / 1024 / 1024;
NumberFormat nf = new DecimalFormat("0.00");
logger.info("图片大小:" + Double.parseDouble(nf.format(imageSize)) + "M");
if (imageSize > uploadImageSize) {
throw new BDException("图片过大,请选择小于 " + uploadImageSize + "M 的图片");
}
return fileType;
}
application.xml
uploadImage:
types: image/gif,image/jpeg,image/png
# 单位M
size: 3
serverUrl: http://127.0.0.1:${server.port}
baseUrl: \upimages\
此时上传的图片根据访问路径还无法直接访问得到,我们需要配置一些东西
/**
* @author : xukun
* @date : 2020/10/20
*/
@Configuration
public class StaticConfig implements WebMvcConfigurer {
private static Logger logger = LoggerFactory.getLogger(StaticConfig.class);
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
String projectDir = System.getProperty("user.dir");
String fileDir = "file:" + projectDir + "\\upimages\\";
// logger.info("FileDir:" + fileDir);
registry.addResourceHandler("/static/**")
.addResourceLocations("classpath:/static/");
//配置访问图片时的对应请求,
registry.addResourceHandler("/upimages/**")//访问上传的图片
.addResourceLocations(fileDir);
WebMvcConfigurer.super.addResourceHandlers(registry);
}
}
当有数据后,我们的数据库表中的数据会是这样的形式
这时,在浏览器访问时取networkurl就可以直接访问。
二、删除图片
删除图片的时候,除了删除数据库的数据,还要删除磁盘中的数据
@Transactional
@Override
public ResultData deletImage() {
logger.info("开始清理");
//与没有关联的图片:status=1
List<UpImageDO> upImageDOList = upImageDao.selectNoLinkList();
int deleteLocalCount = 0;//本地磁盘删除的图片数量
int deleteDataBaseCount = 0;//数据库删除的数量
int localExistCount = 0;//本地存在图片的数量
if (upImageDOList != null) {//有数据
for (UpImageDO upImageDO : upImageDOList) {
//获取该图片本地磁盘路径
String localUrl = upImageDO.getLocalUrl();
int[] localCount = FileUtils.deleteLocalImage(localUrl);
localExistCount += localCount[0];
deleteLocalCount += localCount[1];
int count = upImageDao.deleteById(upImageDO.getId());
deleteDataBaseCount += count;
}
}
deleteNullDir();
deleteTemp();
logger.info("清理完毕");
logger.info("数据库共" + upImageDOList.size() + "条数据,成功清理" + deleteDataBaseCount + "条数据");
logger.info("本地共" + localExistCount + "张图片,成功清理" + deleteLocalCount + "张图片");
return ResultDataUtils.success("数据库数据共" + upImageDOList.size() + "条数据,成功清理" + deleteDataBaseCount + "条数据。本地共" + localExistCount + "张图片,成功清理" + deleteLocalCount + "张图片");
}
/**
* 清理空的文件夹
*/
private void deleteNullDir() {
String rootDir = System.getProperty("user.dir") + uploadImageBaseUrl;
File file = new File(rootDir);
if (file.exists()) {
FileUtils.clearNullDir(file);
}
}
/**
* 清理缓存目录下的所有文件
*/
private void deleteTemp() {
File file = new File(System.getProperty("user.dir") + "\\upimages\\temp\\");
if (file.exists()) {
File[] files = file.listFiles();
for (File file1 : files) {
if (file1.isFile()) {
file1.delete();
}
}
}
}
用到的工具类FileUtils
private static Logger logger = LoggerFactory.getLogger(FileUtils.class);
/**
* 清理指定目录下的空文件夹
*
* @param dir
*/
public static void clearNullDir(File dir) {
File[] dirs = dir.listFiles();
for (int i = 0; i < dirs.length; i++) {
if (dirs[i].isDirectory()) {
clearNullDir(dirs[i]);
}
}
if (dir.isDirectory()) {
dir.delete();
}
}
/**
* 根据路径清理本地图片资源
*
* @param localUrl
* @return int数组[existCount, deleteCount]
*/
public static int[] deleteLocalImage(String localUrl) {
File file = new File(localUrl);
int deleteCount = 0;
int existCount = 0;
if (file.exists()) {
existCount++;
boolean deleteFlag = file.delete();
if (deleteFlag) {
deleteCount++;
}
}
return new int[]{existCount, deleteCount};
}
这样,在删除数据库数据的同时,把多余的图片资源也删除了。
三、网络图片url转MultipartFile
大致分为两步:
1、将网络图片转为File
2、将File转为MultipartFile
FileUtils(附件里面有完整版)
/**
* inputStream 转 File
*/
public static File inputStreamToFile(InputStream ins, String name, String tempDir) throws IOException {
//System.getProperty("java.io.tmpdir")临时目录+File.separator目录中间的间隔符+文件名
// String tempDir = System.getProperty("user.dir") + "\\upimages\\temp\\";
File dir = new File(tempDir);
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(tempDir + name);
OutputStream os = new FileOutputStream(file);
int bytesRead;
int len = 8192;
byte[] buffer = new byte[len];
while ((bytesRead = ins.read(buffer, 0, len)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
ins.close();
return file;
}
/**
* file转multipartFile
*/
public static MultipartFile fileToMultipartFile(File file) throws IOException {
FileItem item = new DiskFileItem("formFieldName",
Files.probeContentType(file.toPath()),
false,
file.getName(),
(int) file.length(),
file.getParentFile());
int bytesRead;
byte[] buffer = new byte[8192];
FileInputStream fis = new FileInputStream(file);
OutputStream os = item.getOutputStream();
while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
fis.close();
return new CommonsMultipartFile(item);
}
/**
* 网络图片url转MultipartFile
*/
public static MultipartFile urlToMultipartFile(String url, String tempPath) {
File file;
MultipartFile multipartFile;
try {
HttpURLConnection httpUrl = (HttpURLConnection) new URL(url).openConnection();
httpUrl.connect();
String[] urls = url.split("\\?");//有的网络图片可能带有参数
String fileSuffixName = urls[0].substring(urls[0].lastIndexOf("."));
file = FileUtils.inputStreamToFile(httpUrl.getInputStream(), System.currentTimeMillis() + fileSuffixName, tempPath);
logger.info("---------" + file + "-------------");
multipartFile = FileUtils.fileToMultipartFile(file);
httpUrl.disconnect();
} catch (IOException e) {
throw new BDException("网络错误");
}
return multipartFile;
}
public static void main(String[] args) {
String tempDir = System.getProperty("user.dir") + "\\upimages\\temp\\";
MultipartFile multipartFile = urlToMultipartFile("http://192.168.1.82:8089/slkj/upimages/2020/11/bfcbdfb3-c4b4-4994-9933-2bb012b2d995.png", tempDir);
System.out.println(multipartFile.getOriginalFilename());
System.out.println(multipartFile.getContentType());
System.out.println(multipartFile.getSize());
System.out.println(multipartFile.getName());
}
四、富文本
1、传输文本
前端拿到富文本里面的数据后,传输给后端,后端进行解析,保存在数据库。
一般前端传给后端的数据格式如下:
<p>测试</p>
后端通过下面代码转为标准格式:
StringEscapeUtils.unescapeHtml()
后端转义后:
<p>测试</p>
2、传输图片和文本
(1)图片以
网络地址
的形式传输:该形式在上传图片的时候调用的是后端接口,img变迁里面src存放的是后端返回的网络地址,推荐适用该形式。
(2)图片以base64
形式传输:该形式适用传输少量并且小的图片,如果出现传输大量图片的情况,会直接卡死,所以不推荐适用该形式传输富文本。下面介绍一下富文本里面传输base64图片的编码后端解析。
BASE64Utils(附件里面有完整版)
/**
* @author : xukun
* @date : 2020/10/21
*/
public class BASE64Utils implements MultipartFile {
private final byte[] imgContent;
private final String header;
public BASE64Utils(byte[] imgContent, String header) {
this.imgContent = imgContent;
this.header = header.split(";")[0];
}
@Override
public String getName() {
// TODO - implementation depends on your requirements
return System.currentTimeMillis() + Math.random() + "." + header.split("/")[1];
}
@Override
public String getOriginalFilename() {
// TODO - implementation depends on your requirements
return System.currentTimeMillis() + (int) Math.random() * 10000 + "." + header.split("/")[1];
}
@Override
public String getContentType() {
// TODO - implementation depends on your requirements
return header.split(":")[1];
}
@Override
public boolean isEmpty() {
return imgContent == null || imgContent.length == 0;
}
@Override
public long getSize() {
return imgContent.length;
}
@Override
public byte[] getBytes() throws IOException {
return imgContent;
}
@Override
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(imgContent);
}
@Override
public void transferTo(File dest) throws IOException, IllegalStateException {
new FileOutputStream(dest).write(imgContent);
}
/**
* base64编码转MultipartFile文件
*
* @param base64 Base64编码
* @return MultipartFile
*/
public static MultipartFile base64ToMultipart(String base64) {
try {
String[] baseStrs = base64.split(",");
BASE64Decoder decoder = new BASE64Decoder();
byte[] b;
b = decoder.decodeBuffer(baseStrs[1]);
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {
b[i] += 256;
}
}
return new BASE64Utils(b, baseStrs[0]);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* 将本地图片转为base64编码
*
* @param localImagePath 本地图片路径
* @return String base64编码
*/
public static String ImageToBase64ByLocal(String localImagePath) {
// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
InputStream in;
byte[] data = null;
// 读取图片字节数组
try {
in = new FileInputStream(localImagePath);
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
// 对字节数组Base64编码
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);// 返回Base64编码过的字节数组字符串
}
/**
* 将图片转为base64
*
* @param networkImageURL 网络图片路径
* @return String base64编码
*/
public static String imageToBase64ByOnline(String networkImageURL) {
ByteArrayOutputStream data = new ByteArrayOutputStream();
try {
// 创建URL
URL url = new URL(networkImageURL);
byte[] by = new byte[1024];
// 创建链接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
InputStream is = conn.getInputStream();
// 将内容读取内存中
int len = -1;
while ((len = is.read(by)) != -1) {
data.write(by, 0, len);
}
// 关闭流
is.close();
} catch (IOException e) {
e.printStackTrace();
}
// 对字节数组Base64编码
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data.toByteArray());
}
public static void main(String[] args) {
// String s = ImageToBase64ByLocal("C:\\Users\\SLDT\\Desktop\\src\\main\\resources\\static\\upimages\\2020\\10\\03ae4fb5-57cd-4372-a825-3cf09d8f6086.png");
// s = "data:image/png;base64,"+s;
// System.out.println(s);
// String s = imageToBase64ByOnline("http://192.168.1.82:8089/upimages/2020/10/03ae4fb5-57cd-4372-a825-3cf09d8f6086.png");
// s = "data:image/png;base64," + s;
// System.out.println(s);
}
}
3、替换前端传过来的html里面的img
/**
* 转换content里面的图片src
*
* @param content 富文本的内容
* @param networkUrlList 富文本中的图片的范文地址列表
* @return
*/
private String parseImage(String content, List<String> networkUrlList) {
Document doc = Jsoup.parseBodyFragment(content);
Elements pngs = doc.select("img");
for (Element element : pngs) {
//获得src
String imgSrc = element.attr("src");
//上传到临时目录,后面上传图片的时候直接从缓存目录取图片二次上传
String tempDir = System.getProperty("user.dir") + "\\upimages\\temp\\";
MultipartFile multipartFile = FileUtils.urlToMultipartFile(imgSrc, tempDir);
//上传文件
ResultData resultData = upImageService.uploadImage(multipartFile);
UpImageDO upImageDO = (UpImageDO) resultData.getData();
networkUrlList.add(upImageDO.getNetworkUrl());
//替换src
imgSrc = upImageDO.getNetworkUrl();
element.attr("src", imgSrc);
}
//禁用文档的完美打印(避免多个空格被合成一个空格)
doc.outputSettings(new Document.OutputSettings().prettyPrint(false));
return doc.body().html();
}
五、附件
完整FileUtils
package com.shenlan.slkj.utils;
import com.shenlan.slkj.exception.BDException;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
/**
* @author : xukun
* @date : 2020/10/26
*/
public class FileUtils {
private static Logger logger = LoggerFactory.getLogger(FileUtils.class);
/**
* 清理指定目录下的空文件夹
*
* @param dir
*/
public static void clearNullDir(File dir) {
File[] dirs = dir.listFiles();
for (int i = 0; i < dirs.length; i++) {
if (dirs[i].isDirectory()) {
clearNullDir(dirs[i]);
}
}
if (dir.isDirectory()) {
dir.delete();
}
}
/**
* 根据路径清理本地图片资源
*
* @param localUrl
* @return int数组[existCount, deleteCount]
*/
public static int[] deleteLocalImage(String localUrl) {
File file = new File(localUrl);
int deleteCount = 0;
int existCount = 0;
if (file.exists()) {
existCount++;
boolean deleteFlag = file.delete();
if (deleteFlag) {
deleteCount++;
}
}
return new int[]{existCount, deleteCount};
}
/**
* inputStream 转 File
*/
public static File inputStreamToFile(InputStream ins, String name, String tempDir) throws IOException {
//System.getProperty("java.io.tmpdir")临时目录+File.separator目录中间的间隔符+文件名
// String tempDir = System.getProperty("user.dir") + "\\upimages\\temp\\";
File dir = new File(tempDir);
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(tempDir + name);
OutputStream os = new FileOutputStream(file);
int bytesRead;
int len = 8192;
byte[] buffer = new byte[len];
while ((bytesRead = ins.read(buffer, 0, len)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
ins.close();
return file;
}
/**
* file转multipartFile
*/
public static MultipartFile fileToMultipartFile(File file) throws IOException {
FileItem item = new DiskFileItem("formFieldName",
Files.probeContentType(file.toPath()),
false,
file.getName(),
(int) file.length(),
file.getParentFile());
int bytesRead;
byte[] buffer = new byte[8192];
FileInputStream fis = new FileInputStream(file);
OutputStream os = item.getOutputStream();
while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
fis.close();
return new CommonsMultipartFile(item);
}
/**
* 网络图片url转MultipartFile
*/
public static MultipartFile urlToMultipartFile(String url, String tempPath) {
File file;
MultipartFile multipartFile;
try {
HttpURLConnection httpUrl = (HttpURLConnection) new URL(url).openConnection();
httpUrl.connect();
String[] urls = url.split("\\?");//有的网络图片可能带有参数
String fileSuffixName = urls[0].substring(urls[0].lastIndexOf("."));
file = FileUtils.inputStreamToFile(httpUrl.getInputStream(), System.currentTimeMillis() + fileSuffixName, tempPath);
logger.info("---------" + file + "-------------");
multipartFile = FileUtils.fileToMultipartFile(file);
httpUrl.disconnect();
} catch (IOException e) {
throw new BDException("网络错误");
}
return multipartFile;
}
public static void main(String[] args) {
String tempDir = System.getProperty("user.dir") + "\\upimages\\temp\\";
MultipartFile multipartFile = urlToMultipartFile("http://192.168.1.82:8089/slkj/upimages/2020/11/bfcbdfb3-c4b4-4994-9933-2bb012b2d995.png", tempDir);
System.out.println(multipartFile.getOriginalFilename());
System.out.println(multipartFile.getContentType());
System.out.println(multipartFile.getSize());
System.out.println(multipartFile.getName());
}
}
完整BASE64Utils
package com.shenlan.slkj.utils;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* @author : xukun
* @date : 2020/10/21
*/
public class BASE64Utils implements MultipartFile {
private final byte[] imgContent;
private final String header;
public BASE64Utils(byte[] imgContent, String header) {
this.imgContent = imgContent;
this.header = header.split(";")[0];
}
@Override
public String getName() {
// TODO - implementation depends on your requirements
return System.currentTimeMillis() + Math.random() + "." + header.split("/")[1];
}
@Override
public String getOriginalFilename() {
// TODO - implementation depends on your requirements
return System.currentTimeMillis() + (int) Math.random() * 10000 + "." + header.split("/")[1];
}
@Override
public String getContentType() {
// TODO - implementation depends on your requirements
return header.split(":")[1];
}
@Override
public boolean isEmpty() {
return imgContent == null || imgContent.length == 0;
}
@Override
public long getSize() {
return imgContent.length;
}
@Override
public byte[] getBytes() throws IOException {
return imgContent;
}
@Override
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(imgContent);
}
@Override
public void transferTo(File dest) throws IOException, IllegalStateException {
new FileOutputStream(dest).write(imgContent);
}
/**
* base64编码转MultipartFile文件
*
* @param base64 Base64编码
* @return MultipartFile
*/
public static MultipartFile base64ToMultipart(String base64) {
try {
String[] baseStrs = base64.split(",");
BASE64Decoder decoder = new BASE64Decoder();
byte[] b;
b = decoder.decodeBuffer(baseStrs[1]);
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {
b[i] += 256;
}
}
return new BASE64Utils(b, baseStrs[0]);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* 将本地图片转为base64编码
*
* @param localImagePath 本地图片路径
* @return String base64编码
*/
public static String ImageToBase64ByLocal(String localImagePath) {
// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
InputStream in;
byte[] data = null;
// 读取图片字节数组
try {
in = new FileInputStream(localImagePath);
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
// 对字节数组Base64编码
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);// 返回Base64编码过的字节数组字符串
}
/**
* 将图片转为base64
*
* @param networkImageURL 网络图片路径
* @return String base64编码
*/
public static String imageToBase64ByOnline(String networkImageURL) {
ByteArrayOutputStream data = new ByteArrayOutputStream();
try {
// 创建URL
URL url = new URL(networkImageURL);
byte[] by = new byte[1024];
// 创建链接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
InputStream is = conn.getInputStream();
// 将内容读取内存中
int len = -1;
while ((len = is.read(by)) != -1) {
data.write(by, 0, len);
}
// 关闭流
is.close();
} catch (IOException e) {
e.printStackTrace();
}
// 对字节数组Base64编码
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data.toByteArray());
}
public static void main(String[] args) {
// String s = ImageToBase64ByLocal("C:\\Users\\SLDT\\Desktop\\src\\main\\resources\\static\\upimages\\2020\\10\\03ae4fb5-57cd-4372-a825-3cf09d8f6086.png");
// s = "data:image/png;base64,"+s;
// System.out.println(s);
// String s = imageToBase64ByOnline("http://192.168.1.82:8089/upimages/2020/10/03ae4fb5-57cd-4372-a825-3cf09d8f6086.png");
// s = "data:image/png;base64," + s;
// System.out.println(s);
}
}