开篇先讲一下我遇到的需求:我是客户给我了一个在快手上爬虫下来的json文件,要求我根据文件的视频链接和图片链接上传到自己的oss上,生成自己的视频图片链接用来给APP播放;基于这种需求我想的思路是先解析json文件,得到视频和图片的路径,然后根据路径将视频和图片下载到本地,再将本地的视频图片上传到oss服务器,然后生成自己的链接存到数据库上,这样视频和图片就变成自己的了,如果需要用到就去数据库取就行了。
话不多说,上代码:
package com.huanxi.util;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.Thumbnails.Builder;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.;
import java.math.BigDecimal;
import java.net.URL;
import java.util.Date;
import java.util.Random;
/*
- @PackgeName: com.liuniu.common.utils.ossutils OSS上传工具类
- @ClassName: OSSClientUtil
- @Author: mi
- Date: 2020/4/6 13:46
- project name: liuniu
- @Version:
- @Description:
*/
public class OSSClientUtil {
private static Logger logger = LoggerFactory.getLogger(OSSClientUtil.class);
private String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
/**
* accessKeyId这里是你的授权KeyId
*/
private String accessKeyId = "";
/**
* 这里是你的授权秘钥
*/
private String accessKeySecret = "";
/**
* 储存空间
*/
private String bucketName = "xiangfeiwenhua-test";
//
/**
* 文件存储目录
* 阿里云API的文件夹名称:视频存放在video文件夹,投资人头像存放在portrait,公司logo存放在logo文件夹,商业计划数存放在business文件夹中
*/
private String filedir ;
private OSSClient ossClient;
/**
* 用于压缩图片 500KB
*/
private static final float PIC_SIZE = 500 * 1024;
/**
* 上传图片时 校验
*/
private static final float SC_PIC_SIZE = 5 * 1024 * 1024;
public OSSClientUtil() {
ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
}
/**
* 初始化
*/
public void init() {
ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
}
/**
* 销毁
*/
public void destory() {
ossClient.shutdown();
}
public String uploadImg2Oss(MultipartFile multipartfile,String type) throws Exception {
filedir=type;
if (multipartfile.getSize()> SC_PIC_SIZE){
throw new CustomException("上传图片大小不能超过5M!");
}
/**
* 获取图片文件名(不带扩展名的文件名)
*/
String prefixName = getFileNameWithoutEx(multipartfile.getOriginalFilename());
/**
* 获取图片后缀名,判断如果是png的话就不进行格式转换,因为Thumbnails存在转png->jpg图片变红bug
*/
String suffixNameOrigin = getExtensionName(multipartfile.getOriginalFilename());
/**
* 图片暂存文件夹
*/
String filePath = "web/src/main/resources/static/statics/images/";
String contextPath = filePath + prefixName + "." + suffixNameOrigin;
/**
* 先转换成jpg
*/
if(contextPath.contains(".png")) {
contextPath =contextPath.replace(".png", ".jpg");
}
//存的项目的中模版图片
File tempFile = null;
//上传时从项目中拿到的图片
File f = null;
InputStream inputStream = null;
try {
//图片在项目中的地址(项目位置+图片名,带后缀名)
tempFile = new File(contextPath);
if (!tempFile.exists()) {
//生成图片文件
FileUtils.copyInputStreamToFile(multipartfile.getInputStream(), tempFile);
}
Builder<BufferedImage> builder = null;
BufferedImage image = ImageIO.read(multipartfile.getInputStream());
/**
* 判断大小,如果小于500kb,不压缩;如果大于等于500kb,压缩
*/
if(tempFile.length()>PIC_SIZE) {
// 计算宽高
int srcWdith = image.getWidth();
int srcHeigth = image.getHeight();
int desWidth = new BigDecimal(srcWdith).multiply(
new BigDecimal(0.8)).intValue();
int desHeight = new BigDecimal(srcHeigth).multiply(
new BigDecimal(0.8)).intValue();
builder = Thumbnails.of(image).size(desWidth, desHeight).keepAspectRatio(false).outputQuality(0.8f);
// 将图片压缩成指定的图片样式
builder.outputFormat("jpg").toFile(contextPath.substring(0, contextPath.indexOf(".")));
}
//获取压缩后的图片
f = new File(contextPath);
inputStream = new FileInputStream(f);
Random random = new Random();
String name = random.nextInt(10000) + System.currentTimeMillis() + ".jpg";
//上传OSS处理
this.uploadFile2OSS(inputStream, name);
return name;
} catch (Exception e) {
throw new Exception("图片上传失败");
} finally {
//将临时文件删除
tempFile.delete();
f.delete();
inputStream.close();
}
}
/**
* 微信支付码 上传OSS
* @param filePath 图片路径
* @param type 类型 oss 存储文件
* @param fileName 文件名称 唯一的
* @return
* @throws Exception
*/
public String weChatOSS(String filePath,String type,String fileName)throws Exception {
filedir=type;
String contextPath =filePath;
//上传时从项目中拿到的图片
File f = null;
InputStream inputStream = null;
try {
f = new File(contextPath);
inputStream = new FileInputStream(f);
//上传OSS处理
this.uploadFile2OSS(inputStream, fileName);
return fileName;
}catch (Exception e) {
throw new Exception("图片上传失败");
} finally {
//将临时文件删除
f.delete();
inputStream.close();
}
}
/**
* 图片 上传阿里云oss
* @param file
* @return
*/
public String uploadHomeFileOSS(MultipartFile file,String type) throws Exception {
filedir=type;
System.out.println(file.getSize());
String originalFilename = file.getOriginalFilename();
String substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
Random random = new Random();
String name = random.nextInt(10000) + System.currentTimeMillis() + substring;
try {
InputStream inputStream = file.getInputStream();
this.uploadFile2OSS(inputStream, name);
return name;
} catch (Exception e) {
throw new Exception("文件上传失败");
}
}
/**
* 上传到OSS服务器 如果同名文件会覆盖服务器上的
*
* @param instream 文件流
* @param fileName 文件名称 包括后缀名
* @return 出错返回"" ,唯一MD5数字签名
*/
public String uploadFile2OSS(InputStream instream, String fileName) {
String ret = "";
try {
//创建上传Object的Metadata
ObjectMetadata objectMetadata = new ObjectMetadata();
objectMetadata.setContentLength(instream.available());
objectMetadata.setCacheControl("no-cache");
objectMetadata.setHeader("Pragma", "no-cache");
objectMetadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf("."))));
objectMetadata.setContentDisposition("inline;filename=" + fileName);
//上传文件
PutObjectResult putResult = ossClient.putObject(bucketName, filedir + fileName, instream, objectMetadata);
ret = putResult.getETag();
} catch (IOException e) {
logger.warn(e.getMessage(), e);
} finally {
try {
if (instream != null) {
instream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return ret;
}
/**
* 获得图片路径
*
* @param fileUrl
* @return
*/
public String getImgUrl(String fileUrl) {
if (!StringUtils.isEmpty(fileUrl)) {
String[] split = fileUrl.split("/");
return this.getUrl(this.filedir + split[split.length - 1]);//this.filedir +
}
return null;
}
/**
* 上传图片
*
* @param url
* @throws
*/
public void uploadImg2Oss(String url) throws IOException {
File fileOnServer = new File(url);
FileInputStream fin;
try {
fin = new FileInputStream(fileOnServer);
String[] split = url.split("/");
this.uploadFile2OSS(fin, split[split.length - 1]);
} catch (FileNotFoundException e) {
throw new IOException("图片上传失败");
}
}
public String uploadImg2Oss(File file) throws IOException {
/* if (file.getSize() > 10 * 1024 * 1024) {
throw new IOException("上传图片大小不能超过10M!");
}*/
String originalFilename = file.getName();
String substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
Random random = new Random();
String name = random.nextInt(10000)+ System.currentTimeMillis() + substring;
try {
BufferedImage image = toBufferedImage(file);//修改图片大小
BufferedImage bufferedImage= Thumbnails.of(image).size(700, 467).asBufferedImage();//修改图片大小
/* BufferedImage bufferedImage= Thumbnails.of(file.getInputStream()).size(700, 467).outputQuality(1).asBufferedImage();*/
this.uploadFile2OSS(bufferedImageToInputStream(bufferedImage), name);//修改图片大小
return name;
} catch (Exception e) {
throw new IOException("图片上传失败");
}
}
//上传视频
public String uploadVideo(File file,String type) throws IOException {
filedir=type;
String originalFilename = file.getName();
String substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
Random random = new Random();
String name = random.nextInt(10000)+ System.currentTimeMillis() + substring;
originalFilename = name;
try {
InputStream stream = new FileInputStream(file);
//MultipartFile multipartFile = new MockMultipartFile(file.getName(), stream);
//InputStream stream=((MultipartFile) file).getInputStream();
//String filename=System.currentTimeMillis()+(multipartFile).getOriginalFilename();
this.uploadFile2OSS(stream, originalFilename);
return name;
} catch (Exception e) {
throw new IOException("图片上传失败");
}
}
/**
* 获得url链接
*
* @param key
* @return
*/
public String getUrl(String key) {
// 设置URL过期时间为10年 3600l* 1000*24*365*10
Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10);
// 生成URL
String productImgUrl = "";
URL url = ossClient.generatePresignedUrl(bucketName, key, expiration);
if (url != null) {
productImgUrl = url.toString().substring(0, url.toString().indexOf("?"));
StringBuilder sb = new StringBuilder(productImgUrl);
productImgUrl = sb.replace(7, 48, StateUtils._videoCdns).toString();
return productImgUrl;
}
return productImgUrl;
}
/**
* Description: 判断OSS服务文件上传时文件的contentType
*
* @param FilenameExtension 文件后缀
* @return String
*/
public static String getcontentType(String FilenameExtension) {
if (FilenameExtension.equalsIgnoreCase(".bmp")) {
return "image/bmp";
}
if (FilenameExtension.equalsIgnoreCase(".gif")) {
return "image/gif";
}
if (FilenameExtension.equalsIgnoreCase(".jpeg") ||
FilenameExtension.equalsIgnoreCase(".jpg") ||
FilenameExtension.equalsIgnoreCase(".png")) {
return "image/jpeg";
}
if (FilenameExtension.equalsIgnoreCase(".html")) {
return "text/html";
}
if (FilenameExtension.equalsIgnoreCase(".txt")) {
return "text/plain";
}
if (FilenameExtension.equalsIgnoreCase(".vsd")) {
return "application/vnd.visio";
}
if (FilenameExtension.equalsIgnoreCase(".pptx") ||
FilenameExtension.equalsIgnoreCase(".ppt")) {
return "application/vnd.ms-powerpoint";
}
if (FilenameExtension.equalsIgnoreCase(".docx") ||
FilenameExtension.equalsIgnoreCase(".doc")) {
return "application/msword";
}
if (FilenameExtension.equalsIgnoreCase(".xml")) {
return "text/xml";
}
return "image/jpeg";
}
/**
* 获取不带扩展名的文件名
*
* @param filename 文件
* @return String
*/
private static String getFileNameWithoutEx(String filename) {
if ((filename != null) && (filename.length() > 0)) {
int dot = filename.lastIndexOf('.');
if ((dot > -1) && (dot < (filename.length()))) {
return filename.substring(0, dot);
}
}
return filename;
}
/**
* 获取文件扩展名
*
* @param filename 文件名
* @return String
*/
public static String getExtensionName(String filename) {
if ((filename != null) && (filename.length() > 0)) {
int dot = filename.lastIndexOf('.');
if ((dot > -1) && (dot < (filename.length() - 1))) {
return filename.substring(dot + 1);
}
}
return filename;
}
/**
* OSS 下载文件
* @param os 输出流
* @param objectName 文件名称
* @throws IOException
*/
public void exportOssFile(OutputStream os, String objectName) throws IOException {
//存储空间名称、文件名称(包含文件存储目录)
OSSObject ossObject = ossClient.getObject(bucketName, objectName);
// 读取文件内容。
BufferedInputStream in = new BufferedInputStream(ossObject.getObjectContent());
BufferedOutputStream out = new BufferedOutputStream(os);
byte[] buffer = new byte[1024];
int lenght = 0;
while ((lenght = in.read(buffer)) != -1) {
out.write(buffer, 0, lenght);
}
if (out != null) {
out.flush();
out.close();
}
if (in != null) {
in.close();
}
}
public static BufferedImage toBufferedImage(File file) {
BufferedImage srcImage = null;
try {
FileInputStream in = (FileInputStream) ((MultipartFile) file).getInputStream();
srcImage = javax.imageio.ImageIO.read(in);
} catch (IOException e) {
}
return srcImage;
}
public InputStream bufferedImageToInputStream(BufferedImage image){
ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
ImageIO.write(image, "jpg", os);
InputStream input = new ByteArrayInputStream(os.toByteArray());
return input;
} catch (IOException e) {
logger.error("提示:",e);
}
return null;
}
}
以上代码是配置oss的工具类,只需要将授权KeyId:accessKeyId、授权秘钥:accessKeySecret、储存空间:bucketName修改为自己的,然后拿来用即可,其他都是上传的方法类不必修改,因为我用的是阿里云oss,所以我的key和秘钥是配的阿里云的api的key和秘钥(不知道key和秘钥的小伙伴可以访问https://usercenter.console.aliyun.com/?accounttraceid=c934212b7d4a4ff1b210449e20e678f3jwzh#/manage/ak网址来查看自己的key和秘钥),储存空间就是你上传的视频图片存储到oss的哪个文件夹下
接下来是解析主类了,不多比比上代码:
控制层:
/**
* 解析文件生成列表
* @return List<Map<String,Object>>
*/
@RequestMapping(value = "/resolveFile", method = RequestMethod.POST)
@ApiOperation(value = "文件解析列表", httpMethod = "POST")
@ApiImplicitParams({@ApiImplicitParam(name = "resolveFilePath", value = "需要解析文件的路径"),@ApiImplicitParam(name = "savaPath", value = "保存路径"),@ApiImplicitParam(name = "videoFormt", value = "解析视频的格式,如.mp4"),@ApiImplicitParam(name = "coverFormt", value = "解析视频封面的格式,如.jpg"),})
public AjaxResult resolveFile(String resolveFilePath, String savaPath, String videoFormt, String coverFormt) {
if (StringUtils.isEmpty(resolveFilePath)) {
return AjaxResult.error("解析文件的路径不能为空");
}
if (StringUtils.isEmpty(savaPath)) {
return AjaxResult.error("保存路径不能为空");
}
if (StringUtils.isEmpty(videoFormt)) {
return AjaxResult.error("解析视频的格式不能为空,请输入.mp4等视频格式");
}
if (StringUtils.isEmpty(coverFormt)) {
return AjaxResult.error("解析视频封面的格式不能为空,请输入.jpg等图片格式");
}
return exportService.resolveFile(resolveFilePath, savaPath, videoFormt, coverFormt);
}
主体业务层:
@Transactional
@Override
public AjaxResult resolveFile(String resolveFilePath, String savaPath, String videoFormt, String coverFormt) {
//存放Author实体的集合(用来传输数据)
List<AuthorEntity> authorList = new ArrayList<AuthorEntity>();
//存放Author实体的集合(用来数据库添加)
List<AuthorEntity> addAuthorList = new ArrayList<AuthorEntity>();
//存放Video实体的集合(用来传输数据和数据库添加)
List<VideoEntity> videoList = new ArrayList<VideoEntity>();
String morenAvatar = "https://xiangfeiwenhua-image.oss-cn-hangzhou.aliyuncs.com/avatar/111avatar.jpg";
File file = new File(resolveFilePath);
try {
//判断文件夹是否存在
if (file.exists()) {
//判断是否是文件
if (file.isDirectory()) {
File[] fileLists = file.listFiles();
//若判断File为目录则调用判断文件的递归方法
List<Map<String, String>> fileList = isFile(fileLists, new ArrayList<Map<String, String>>());
for (int i = 0; i < fileList.size(); i++) {
//作者实体
AuthorEntity author = new AuthorEntity();
if (StringUtils.isNotNull(fileList.get(i).get("author"))) {
//解析作者文件
JSONObject jsonObject = JSONObject.parseObject(fileList.get(i).get("author"));
String data = jsonObject.getString("data");
if (StringUtils.isNotNull(data)) {
JSONObject dataJson = JSONObject.parseObject(data);
//文件信息
String profile = dataJson.getString("profile");
if (StringUtils.isNotNull(profile)) {
JSONObject profileJson = JSONObject.parseObject(profile);
//存作者表的member_id
int memberId = Integer.parseInt(profileJson.getString("userId"));
author.setMemberId(memberId);
//存作者表的nickname
String nickname = profileJson.getString("userName");
author.setNickname(nickname);
//存作者表的desc
String desc = profileJson.getString("userText");
author.setAuthorDesc(desc);
//存作者表的avatar
String avatar = "http:" + profileJson.getString("headurl");
author.setAvatar(avatar);
//存作者表的province
String province = profileJson.getString("province");
author.setProvince(province);
//存作者表的city
String city = profileJson.getString("city");
author.setCity(city);
//存作者表的sex
String sex = "";
if ("M".equals(profileJson.getString("userSex"))) {
sex = "0";
} else if ("F".equals(profileJson.getString("userSex"))) {
sex = "1";
}
author.setSex(sex);
//存作者表的tags
String tags = dataJson.getString("contentTags");
author.setTags(tags);
//存作者表的type
String type = dataJson.getString("type");
author.setType(type);
//存作者表的createdAt
author.setCreatedAt(new Date());
//查询这个作者是否在表中存在
AuthorEntity authorEntity = authorMapper.findAuthorById(memberId);
//用来传输数据
authorList.add(author);
//用来添加数据
if (null == authorEntity) {
addAuthorList.add(author);
}
}
}
} else if (StringUtils.isNotNull(fileList.get(i).get("content"))) {
//解析视频文件
JSONObject jsonObject = JSONObject.parseObject(fileList.get(i).get("content"));
String data = jsonObject.getString("data");
if (StringUtils.isNotNull(data)) {
JSONObject dataJson = JSONObject.parseObject(data);
String list = dataJson.getString("list");
List<VideoEntity> list1 = new ArrayList<VideoEntity>();
list1 = JSONObject.parseArray(list, VideoEntity.class);
if(null != list1 && list1.size() > 0) {
for (int j = 0; j < list1.size(); j++) {
//视频的实体
VideoEntity videoEntity = new VideoEntity();
try {
//存视频表的video
String videos = list1.get(j).getMvUrl();
//将视频下载到本地
String videoUrl = downLoadFromUrl(videos, videoFormt, savaPath);
File videoFile = new File(videoUrl);
OSSClientUtil ossClientvideo = new OSSClientUtil();
//将文件上传
String nameVideo = ossClientvideo.uploadVideo(videoFile, "Video/");
//获取文件的URl地址 以便前台 显示
String videoUrls = ossClientvideo.getImgUrl(nameVideo);
logger.debug("视频" + i + j);
logger.debug(videos);
videoEntity.setVideo(videoUrls);
} catch (Exception e) {
e.printStackTrace();
}
try {
//存视频表的cover
String cover = "http:" + list1.get(j).getCover();
//将封面下载到本地
String coverUrl = downLoadFromUrl(cover, coverFormt, savaPath);
File coverFile = new File(coverUrl);
OSSClientUtil ossClientCo = new OSSClientUtil();
//将文件上传
String nameCo = ossClientCo.uploadVideo(coverFile, "cover/");
//获取文件的URl地址 以便前台 显示
String coverUrls = ossClientCo.getImgUrl(nameCo);
logger.debug("封面" + i + j);
logger.debug("封面" + cover);
videoEntity.setCover(coverUrls);
} catch (Exception e) {
e.printStackTrace();
}
//存视频的caption
String caption = list1.get(j).getCaption();
videoEntity.setCaption(caption);
//存视频的like
String like = list1.get(j).getLikeCount();
videoEntity.setUserLike(like);
//存视频的comment
String comment = list1.get(j).getCommentCount();
videoEntity.setUserComment(comment);
//存视频的focus
String focus = "0";
videoEntity.setFocus(focus);
//存视频的duration
// String duration = list1.get(j).getDuration().toString();
if (list1.get(j).getDuration() == null) {
videoEntity.setDuration(0);
} else {
videoEntity.setDuration(list1.get(j).getDuration());
}
//存视频的author_id
int authorId = list1.get(j).getUserId();
videoEntity.setAuthorId(authorId);
videoEntity.setAvatar(morenAvatar);
for (int k = 0; k < authorList.size(); k++) {
if (authorList.get(k).getMemberId() == authorId) {
try {
//将头像下载到本地
String avatarUrl = downLoadFromUrl(authorList.get(k).getAvatar(), coverFormt, savaPath);
File avatarFile = new File(avatarUrl);
OSSClientUtil ossClient = new OSSClientUtil();
//将文件上传
String name = ossClient.uploadVideo(avatarFile, "avatar/");
//获取文件的URl地址 以便前台 显示
String avatarUrls = ossClient.getImgUrl(name);
logger.debug("头像地址" + i + j);
logger.debug("头像地址" + authorList.get(k).getAvatar());
videoEntity.setAvatar(avatarUrls);
} catch (Exception e) {
e.printStackTrace();
}
break;
}
}
videoList.add(videoEntity);
}
}
}
}
}
} else if (file.isFile()) {
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
StringBuffer sf = new StringBuffer();
char[] arr = new char[10];
int num;
while ((num = in.read(arr)) != -1) {
sf.append(new String(arr, 0, num));
}
//判断文件内容是否符合json格式
if (isJson(sf.toString())) {
logger.debug("得传文件夹啊");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
} catch (Exception e) {
logger.debug("文件不存在");
e.printStackTrace();
}
//将数据新增到数据库中
if (null != videoList && videoList.size() != 0) {
videoMapper.addDiveoBatch(videoList);
}
//将数据新增到数据库中
if (null != addAuthorList && addAuthorList.size() != 0) {
authorMapper.addAuthorBatch(addAuthorList);
}
return AjaxResult.success("上传oss成功");
}
业务主体方法调用的封装方法:
/**
* 通过url将文件下载到本地
*
* @return
*/
public static String downLoadFromUrl(String urlStr, String format, String savePath) throws IOException {
String fileName = IdUtils.randomUUID() + format;
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//设置超时间为3秒
conn.setConnectTimeout(3 * 1000);
//防止屏蔽程序抓取而返回403错误
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
//得到输入流
InputStream inputStream = conn.getInputStream();
//获取自己数组
byte[] getData = readInputStream(inputStream);
//文件保存位置
File saveDir = new File(savePath);
if (!saveDir.exists()) {
saveDir.mkdir();
}
File file = new File(saveDir + File.separator + fileName);
FileOutputStream fos = new FileOutputStream(file);
fos.write(getData);
if (fos != null) {
fos.close();
}
if (inputStream != null) {
inputStream.close();
}
return saveDir + File.separator + fileName;
}
/**
* 从输入流中获取字节数组
*
* @param inputStream
* @return
* @throws IOException
*/
public static byte[] readInputStream(InputStream inputStream) throws IOException {
byte[] buffer = new byte[1024];
int len = 0;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while ((len = inputStream.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
bos.close();
return bos.toByteArray();
}
主要逻辑都在业务层中。我是传入参数1.你需要解析的json文件路径(因为我写的接口没接入前端所以接受的是文件的路径,你要是接入前端的话可以用MultipartFile文件类来接收,如果你要是解析的Excel文件的话用POI来解析就行,因为后期的变动我就重写了这些需求,这里就不展示了)2.保存到本地的文件路径3.解析视频的格式4.解析图片的格式。这里有一个坏处就是解析的视频图片都到本地了很占用内存,建议上传完就将本地视频图片删除;还有可以将要上传的图片视频分为多批次上传,比如一次10个,这样就不会报数据库连接超时的错误。希望这篇文章对你有用。