记得上下班打卡 | git大法好,push需谨慎

Commit 641e7db6 authored by jiangxiulong's avatar jiangxiulong

老的阿里云上传整理优化

parent 569153be
...@@ -8,9 +8,12 @@ import java.math.BigInteger; ...@@ -8,9 +8,12 @@ import java.math.BigInteger;
import java.net.HttpURLConnection; import java.net.HttpURLConnection;
import java.net.URL; import java.net.URL;
import java.security.MessageDigest; import java.security.MessageDigest;
import java.time.LocalDateTime;
import java.util.UUID;
/** /**
* aloss 上传MultipartFile to File * aloss 上传MultipartFile to File
*
* @author jiangxiulong * @author jiangxiulong
* @since 2021-06-10 * @since 2021-06-10
*/ */
...@@ -22,19 +25,21 @@ public class FilesUtils { ...@@ -22,19 +25,21 @@ public class FilesUtils {
* @param file * @param file
* @throws Exception * @throws Exception
*/ */
public static File multipartFileToFile(MultipartFile file) throws Exception { public static File multipartFileToFile(MultipartFile file) {
try {
File toFile = null; File toFile = null;
if (file.equals("") || file.getSize() <= 0) { if (!file.equals("") && file.getSize() > 0) {
file = null; InputStream ins = null;
} else { ins = file.getInputStream();
InputStream ins = null; toFile = new File(file.getOriginalFilename());
ins = file.getInputStream(); inputStreamToFile(ins, toFile);
toFile = new File(file.getOriginalFilename()); ins.close();
inputStreamToFile(ins, toFile); }
ins.close(); return toFile;
} catch (Exception e) {
log.error("multipartFileToFileError", e);
return null;
} }
return toFile;
} }
//获取流文件 //获取流文件
...@@ -55,20 +60,22 @@ public class FilesUtils { ...@@ -55,20 +60,22 @@ public class FilesUtils {
/** /**
* 删除本地临时文件 * 删除本地临时文件
*
* @param file * @param file
*/ */
public static void delteTempFile(File file) { public static void deleteTempFile(File file) {
try { try {
if (file != null) { if (file != null) {
file.delete(); file.delete();
} }
} catch (Exception e) { } catch (Exception e) {
log.error("delteTempFileError", e); log.error("deleteTempFileError", e);
} }
} }
/** /**
* 获取文件的md5值 * 获取文件的md5值
*
* @param file 文件 * @param file 文件
* @return 返回文件的md5值字符串 * @return 返回文件的md5值字符串
*/ */
...@@ -100,7 +107,14 @@ public class FilesUtils { ...@@ -100,7 +107,14 @@ public class FilesUtils {
} }
} }
public static File inputStreamToFile(String url, String name){ /**
* 大美 通过URL上传
*
* @param url
* @param name
* @return
*/
public static File inputStreamToFile(String url, String name) {
try { try {
HttpURLConnection httpUrl = (HttpURLConnection) new URL(url).openConnection(); HttpURLConnection httpUrl = (HttpURLConnection) new URL(url).openConnection();
httpUrl.connect(); httpUrl.connect();
...@@ -119,9 +133,43 @@ public class FilesUtils { ...@@ -119,9 +133,43 @@ public class FilesUtils {
os.close(); os.close();
ins.close(); ins.close();
return file; return file;
}catch (Exception e){ } catch (Exception e) {
e.printStackTrace(); log.error("inputStreamToFileUrlError", e);
return null; return null;
} }
} }
/**
* 获取上传含文件名的完整路径 这里文件名用了uuid 防止重复,可以根据自己的需要来写
*
* @param pathName banner
* @param filename time.jpeg
* @return
*/
public static String getUploadPath(String pathName, String filename) {
// 078a77e0-cf80-481b-824c-5935247cff15.jpeg
String uploadName = UUID.randomUUID() + filename.substring(filename.lastIndexOf("."));
// 078a77e0cf80481b824c5935247cff15.jpeg
uploadName = uploadName.replace("-", "");
return pathName + "/" + DateUtil.format(LocalDateTime.now(), DateUtil.Formatter.yyyy_MM_dd2) + "/" + uploadName;
}
/**
* 获取 bucketName
*
* @param buckType
* @return
*/
public static String getBucketName(int buckType) {
String bucketName = "img-zhengzai-tv";
switch (buckType) {
case 1:
bucketName = "img-zhengzai-tv";
break;
case 2:
bucketName = "app-zhengzai-tv";
break;
}
return bucketName;
}
} }
...@@ -8,7 +8,6 @@ import com.aliyun.oss.model.ProcessObjectRequest; ...@@ -8,7 +8,6 @@ import com.aliyun.oss.model.ProcessObjectRequest;
import com.aliyun.oss.model.PutObjectRequest; import com.aliyun.oss.model.PutObjectRequest;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils; import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.liquidnet.commons.lang.util.CollectionUtil;
import com.liquidnet.commons.lang.util.DateUtil; import com.liquidnet.commons.lang.util.DateUtil;
import com.liquidnet.commons.lang.util.FilesUtils; import com.liquidnet.commons.lang.util.FilesUtils;
import com.liquidnet.commons.lang.util.IDGenerator; import com.liquidnet.commons.lang.util.IDGenerator;
...@@ -23,7 +22,10 @@ import io.swagger.annotations.ApiOperation; ...@@ -23,7 +22,10 @@ import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils; import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import java.io.File; import java.io.File;
...@@ -69,71 +71,104 @@ public class AlOssController { ...@@ -69,71 +71,104 @@ public class AlOssController {
@RequestParam(defaultValue = "1", required = false) int buckType, @RequestParam(defaultValue = "1", required = false) int buckType,
@RequestParam(defaultValue = "0", required = false) int resize @RequestParam(defaultValue = "0", required = false) int resize
) { ) {
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); File fileNew = FilesUtils.multipartFileToFile(file);
if (null == fileNew) {
return ResponseDto.failure("上传失败");
}
File fileNew = null; // 是否上传过 有直接返回
try { PlatformOssFiles ossFile = this.getOldOssFile(fileNew);
fileNew = FilesUtils.multipartFileToFile(file); UploadVo uploadVo = new UploadVo();
} catch (Exception e) { if (null == ossFile) {
return null; // 上传
ossFile = this.uploadOssFile(file, pathName, buckType, resize, fileNew);
} }
BeanUtils.copyProperties(ossFile, uploadVo);
// file md5 // 删除临时文件 因为老文件也生成了所以也要删除
String fileMD5 = FilesUtils.getFileMD5(fileNew); FilesUtils.deleteTempFile(fileNew);
return ResponseDto.success(uploadVo);
}
/**
* 获取老的上传文件
* @param file
* @return
*/
private PlatformOssFiles getOldOssFile(File file) {
String fileMD5 = FilesUtils.getFileMD5(file);
List<PlatformOssFiles> platformOssFiles = platformOssFilesMapper.selectList( List<PlatformOssFiles> platformOssFiles = platformOssFilesMapper.selectList(
Wrappers.lambdaQuery(PlatformOssFiles.class) Wrappers.lambdaQuery(PlatformOssFiles.class)
.eq(PlatformOssFiles::getMd5str, fileMD5) .eq(PlatformOssFiles::getMd5str, fileMD5)
); );
UploadVo uploadVo = new UploadVo();
if (CollectionUtils.isEmpty(platformOssFiles)) { if (CollectionUtils.isEmpty(platformOssFiles)) {
String filename = file.getResource().getFilename();// time.jpeg return null;
//这里文件名用了uuid 防止重复,可以根据自己的需要来写 } else {
String uploadName = UUID.randomUUID() + filename.substring(filename.lastIndexOf("."));// 078a77e0-cf80-481b-824c-5935247cff15.jpeg return platformOssFiles.get(0);
uploadName = uploadName.replace("-", "");// 078a77e0cf80481b824c5935247cff15.jpeg }
String uploadpath = pathName + "/" + DateUtil.format(LocalDateTime.now(), DateUtil.Formatter.yyyy_MM_dd2) + "/" + uploadName; }
String buckName = "img-zhengzai-tv";
if (2 == buckType) {
buckName = "app-zhengzai-tv";
}
PutObjectRequest putObjectRequest = new PutObjectRequest(buckName, uploadpath, fileNew);
ossClient.putObject(putObjectRequest);
if (resize > 0) {
// 将图片缩放
StringBuilder sbStyle = new StringBuilder();
Formatter styleFormatter = new Formatter(sbStyle);
String styleType = "image/resize,w_" + resize;
// String styleType = "image/resize,m_fixed,w_100,h_100";
styleFormatter.format("%s|sys/saveas,o_%s,b_%s", styleType,
BinaryUtil.toBase64String(uploadpath.getBytes()),
BinaryUtil.toBase64String(buckName.getBytes()));
ProcessObjectRequest request = new ProcessObjectRequest(buckName, uploadpath, sbStyle.toString());
GenericResult processResult = ossClient.processObject(request);
}
ossClient.shutdown(); /**
* 上传文件
* @param file
* @param pathName
* @param buckType
* @param resize
* @param fileNew
* @return
*/
private PlatformOssFiles uploadOssFile(MultipartFile file, String pathName, int buckType, int resize, File fileNew) {
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
String filename = file.getResource().getFilename();
String uploadPath = FilesUtils.getUploadPath(pathName, filename);
String bucketName = FilesUtils.getBucketName(buckType);
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, uploadPath, fileNew);
ossClient.putObject(putObjectRequest);
if (resize > 0) { // 裁切
this.ossFileResize(resize, uploadPath, bucketName, ossClient);
}
// 入库 ossClient.shutdown();
PlatformOssFiles platformOssFilesDate = new PlatformOssFiles();
String ossFilesId = IDGenerator.nextSnowId();
platformOssFilesDate.setOssFilesId(ossFilesId);
platformOssFilesDate.setOssPath(uploadpath);
platformOssFilesDate.setFileName(filename);
platformOssFilesDate.setContentType(file.getContentType());
platformOssFilesDate.setSize((int) file.getSize());
platformOssFilesDate.setMd5str(fileMD5);
platformOssFilesDate.setBuckType(buckType);
platformOssFilesDate.setCreatedAt(DateUtil.getNowTime());
platformOssFilesMapper.insert(platformOssFilesDate);
BeanUtils.copyProperties(platformOssFilesDate, uploadVo); // 入库
} else { PlatformOssFiles platformOssFilesDate = new PlatformOssFiles();
PlatformOssFiles platformOssFilesOne = platformOssFiles.get(0); String ossFilesId = IDGenerator.nextSnowId();
BeanUtils.copyProperties(platformOssFilesOne, uploadVo); platformOssFilesDate.setOssFilesId(ossFilesId);
} platformOssFilesDate.setOssPath(uploadPath);
platformOssFilesDate.setFileName(filename);
platformOssFilesDate.setContentType(file.getContentType());
platformOssFilesDate.setSize((int) file.getSize());
String fileMD5 = FilesUtils.getFileMD5(fileNew);
platformOssFilesDate.setMd5str(fileMD5);
platformOssFilesDate.setBuckType(buckType);
platformOssFilesDate.setCreatedAt(DateUtil.getNowTime());
platformOssFilesMapper.insert(platformOssFilesDate);
FilesUtils.delteTempFile(fileNew); // 删除临时文件 return platformOssFilesDate;
}
return ResponseDto.success(uploadVo); /**
* oss图片裁切
* @param resize
* @param uploadPath
* @param bucketName
* @param ossClient
* @return
*/
private GenericResult ossFileResize(int resize, String uploadPath, String bucketName, OSS ossClient) {
// 将图片缩放
StringBuilder sbStyle = new StringBuilder();
Formatter styleFormatter = new Formatter(sbStyle);
String styleType = "image/resize,w_" + resize;
// String styleType = "image/resize,m_fixed,w_100,h_100";
styleFormatter.format("%s|sys/saveas,o_%s,b_%s", styleType,
BinaryUtil.toBase64String(uploadPath.getBytes()),
BinaryUtil.toBase64String(bucketName.getBytes()));
ProcessObjectRequest request = new ProcessObjectRequest(bucketName, uploadPath, sbStyle.toString());
GenericResult processResult = ossClient.processObject(request);
return processResult;
} }
@PostMapping("/uploadUrl") @PostMapping("/uploadUrl")
...@@ -184,7 +219,7 @@ public class AlOssController { ...@@ -184,7 +219,7 @@ public class AlOssController {
BeanUtils.copyProperties(platformOssFilesOne, uploadVo); BeanUtils.copyProperties(platformOssFilesOne, uploadVo);
} }
FilesUtils.delteTempFile(fileNew); // 删除临时文件 FilesUtils.deleteTempFile(fileNew); // 删除临时文件
return ResponseDto.success(uploadVo); return ResponseDto.success(uploadVo);
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment