阿里OSS文件上传
Controller
package com.zft.web.controller.common;
import com.zft.adaptor.common.constants.FileConstants;
import com.zft.adaptor.utils.file.CompressUtil;
import com.zft.adaptor.utils.file.FileTypeUtil;
import com.zft.domain.service.common.FileService;
import com.zft.domain.service.common.dto.FileAddressDto;
import com.zft.web.common.BaseResponse;
import com.zft.domain.common.HttpStatus;
import com.zft.web.common.ResultBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Objects;
/**
* @author life
* Create on 2023/2/11.
*/
@Slf4j
@RestController
@RequestMapping(path = "/api/file/V1.0", produces = "application/json")
public class FileController {
@Autowired
private FileService fileService;
@PostMapping("/uploadFile")
public BaseResponse<FileAddressDto> uploadFile(MultipartFile file) {
String filename = file.getOriginalFilename();
if (Objects.isNull(filename)) {
return ResultBuilder.buildErrorResult(HttpStatus.PARAM_ERROR_REQUIRED);
}
try {
byte[] bytes = file.getBytes();
String objectName = CompressUtil.getPath(filename);
FileAddressDto addressDto;
if (FileTypeUtil.isPhoto(filename)) {
// 考虑成本压缩文件 调用图片压缩方法
bytes = CompressUtil.compressPicForScale(bytes, CompressUtil.MAX_SIZE);
InputStream inputStream = new ByteArrayInputStream(bytes);
addressDto = fileService.uploadPhotoFile(FileConstants.BUCKET_NAME, objectName, inputStream);
} else {
InputStream inputStream = new ByteArrayInputStream(bytes);
addressDto = fileService.uploadPhotoFile(FileConstants.BUCKET_NAME, objectName, inputStream);
}
return ResultBuilder.buildSuccessResult(addressDto);
} catch (Exception e) {
log.error("FileController uploadFile error", e);
return ResultBuilder.buildErrorResult(HttpStatus.FILE_ERROR_UPLOAD);
}
}
@PostMapping(value = "/downloadFile", produces = {MediaType.APPLICATION_OCTET_STREAM_VALUE, MediaType.APPLICATION_JSON_VALUE})
public BaseResponse<Object> downloadFile(String fileName, HttpServletRequest request, HttpServletResponse response) {
if (Objects.isNull(fileName)) {
return ResultBuilder.buildErrorResult(HttpStatus.PARAM_ERROR_REQUIRED);
}
InputStream inputStream = null;
BufferedOutputStream outputStream = null;
try {
inputStream = fileService.downloadFile(FileConstants.BUCKET_NAME, fileName);
response.reset();
response.setHeader("Content-disposition", "attachment;filename=" + setFileDownloadHeader(request, fileName));
response.setContentType("application/octet-stream;charset=UTF-8");
outputStream = new BufferedOutputStream(response.getOutputStream());
if (inputStream != null) {
int len;
while ((len = inputStream.read()) != -1) {
outputStream.write(len);
outputStream.flush();
}
}
} catch (Exception e) {
log.error("FileController downloadFile error", e);
return ResultBuilder.buildErrorResult(HttpStatus.FILE_ERROR_UPLOAD);
} finally {
if (Objects.nonNull(inputStream)) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (Objects.nonNull(outputStream)) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
public static String setFileDownloadHeader(HttpServletRequest request, String fileName) throws UnsupportedEncodingException {
final String agent = request.getHeader("USER-AGENT");
String filename = fileName;
if (agent.contains("MSIE")) {
// IE浏览器
filename = URLEncoder.encode(filename, "utf-8");
filename = filename.replace("+", " ");
} else if (agent.contains("Firefox")) {
// 火狐浏览器
filename = new String(fileName.getBytes(), "ISO8859-1");
} else if (agent.contains("Chrome")) {
// google浏览器
filename = URLEncoder.encode(filename, "utf-8");
} else {
// 其它浏览器
filename = URLEncoder.encode(filename, "utf-8");
}
return filename;
}
}
Service
业务层接口
package com.zft.domain.service.common;
import com.zft.adaptor.common.exception.BusinessException;
import com.zft.domain.service.common.dto.FileAddressDto;
import java.io.InputStream;
/**
* @author life
* Create on 2023/2/11.
*/
public interface FileService {
/**
* 创建Bucket
*
* @param bucketName Bucket名称
*/
String createBucket(String bucketName) throws BusinessException;
/**
* 上传图片文件
*
* @param inputStream 文件流
* @param bucketName Bucket名称
* @param objectName Object完整路径,例如exampledir/exampleobject.txt
*/
FileAddressDto uploadPhotoFile(String bucketName, String objectName, InputStream inputStream) throws BusinessException;
/**
* 上传非图片文件
*
* @param inputStream 文件流
* @param bucketName Bucket名称
* @param objectName Object完整路径,例如exampledir/exampleobject.txt
*/
void uploadFile(String bucketName, String objectName, InputStream inputStream) throws BusinessException;
/**
* 下载文件
*
* @param bucketName Bucket名称
* @param objectName Object完整路径,例如exampledir/exampleobject.txt
*/
InputStream downloadFile(String bucketName, String objectName) throws BusinessException;
}
业务层实现
package com.zft.domain.service.common.impl;
import com.zft.adaptor.common.exception.BusinessException;
import com.zft.adaptor.rpc.AliYunOssService;
import com.zft.domain.service.common.FileService;
import com.zft.domain.service.common.convertor.FileConvertor;
import com.zft.domain.service.common.dto.FileAddressDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.InputStream;
/**
* @author life
* Create on 2023/2/11.
*/
@Slf4j
@Service("fileService")
public class FileServiceImpl implements FileService {
@Autowired
private AliYunOssService aliYunOssService;
@Override
public String createBucket(String bucketName) throws BusinessException {
return aliYunOssService.createBucket(bucketName);
}
@Override
public FileAddressDto uploadPhotoFile(String bucketName, String objectName, InputStream inputStream) throws BusinessException {
return FileConvertor.INSTANCE.do2Dto(aliYunOssService.uploadPhotoFile(bucketName, objectName, inputStream));
}
@Override
public void uploadFile(String bucketName, String objectName, InputStream inputStream) throws BusinessException {
aliYunOssService.uploadFile(bucketName, objectName, inputStream);
}
@Override
public InputStream downloadFile(String bucketName, String objectName) throws BusinessException {
return aliYunOssService.downloadFile(bucketName, objectName);
}
}
阿里接口
package com.zft.adaptor.rpc;
import com.zft.adaptor.common.exception.BusinessException;
import com.zft.adaptor.rpc.dto.FileAddressDo;
import java.io.InputStream;
/**
* @author life
* Create on 2023/2/11.
*/
public interface AliYunOssService {
/**
* 创建Bucket
*
* @param bucketName Bucket名称
*/
String createBucket(String bucketName) throws BusinessException;
/**
* 上传图片文件
*
* @param inputStream 文件流
* @param bucketName Bucket名称
* @param objectName Object完整路径,例如exampledir/exampleobject.txt
*/
FileAddressDo uploadPhotoFile(String bucketName, String objectName, InputStream inputStream) throws BusinessException;
/**
* 上传非图片文件
*
* @param inputStream 文件流
* @param bucketName Bucket名称
* @param objectName Object完整路径,例如exampledir/exampleobject.txt
*/
void uploadFile(String bucketName, String objectName, InputStream inputStream) throws BusinessException;
/**
* 下载文件
*
* @param bucketName Bucket名称
* @param objectName Object完整路径,例如exampledir/exampleobject.txt
*/
InputStream downloadFile(String bucketName, String objectName) throws BusinessException;
}
阿里实现
package com.zft.adaptor.rpc.impl;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
import com.zft.adaptor.common.exception.BusinessException;
import com.zft.adaptor.rpc.AliYunOssService;
import com.zft.adaptor.rpc.dto.FileAddressDo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.io.*;
import java.util.Date;
/**
* @author life
* Create on 2023/2/10.
*/
@Slf4j
@Service("aliYunOssService")
public class AliYunOssServiceImpl implements AliYunOssService {
private final static String ENDPOINT = "https://*********.com";
private final static String ACCESS_KEY_ID = "*********";
private final static String ACCESS_KEY_SECRET = "*********";
@Override
public String createBucket(String bucketName) throws BusinessException {
OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
try {
ossClient.createBucket(bucketName);
} catch (OSSException oe) {
log.error("Caught an OSSException, which means your request made it to OSS, but was rejected with an error response for some reason.");
log.error("Error Message:" + oe.getErrorMessage());
log.error("Error Code:" + oe.getErrorCode());
log.error("Request ID:" + oe.getRequestId());
log.error("Host ID:" + oe.getHostId());
throw new BusinessException("创建Bucket" + oe.getMessage());
} catch (ClientException ce) {
log.error("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
log.error("Error Message:" + ce.getMessage());
throw new BusinessException("创建Bucket" + ce.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
return bucketName;
}
@Override
public FileAddressDo uploadPhotoFile(String bucketName, String objectName, InputStream inputStream) throws BusinessException {
OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
try {
ObjectMetadata objectMetadata = new ObjectMetadata();
objectMetadata.setContentType(getContentType(objectName.substring(objectName.lastIndexOf("."))));
ossClient.putObject(bucketName, objectName, inputStream, objectMetadata);
Date expiration = new Date(System.currentTimeMillis() + 3600 * 1000);
String url = ossClient.generatePresignedUrl(bucketName, objectName, expiration).toString();
return FileAddressDo.builder().fileUrl(url).objectName(objectName).build();
} catch (OSSException oe) {
log.error("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
log.error("Error Message:" + oe.getErrorMessage());
log.error("Error Code:" + oe.getErrorCode());
log.error("Request ID:" + oe.getRequestId());
log.error("Host ID:" + oe.getHostId());
throw new BusinessException("文件上传失败" + oe.getMessage());
} catch (ClientException ce) {
log.error("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
log.error("Error Message:" + ce.getMessage());
throw new BusinessException("文件上传失败" + ce.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
@Override
public void uploadFile(String bucketName, String objectName, InputStream inputStream) throws BusinessException {
OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
try {
ObjectMetadata objectMetadata = new ObjectMetadata();
objectMetadata.setContentType(getContentType(objectName.substring(objectName.lastIndexOf("."))));
ossClient.putObject(bucketName, objectName, inputStream, objectMetadata);
Date expiration = new Date(System.currentTimeMillis() + 315360000L * 1000);
String url = ossClient.generatePresignedUrl(bucketName, objectName, expiration).toString();
log.info(url);
} catch (OSSException oe) {
log.error("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
log.error("Error Message:" + oe.getErrorMessage());
log.error("Error Code:" + oe.getErrorCode());
log.error("Request ID:" + oe.getRequestId());
log.error("Host ID:" + oe.getHostId());
throw new BusinessException("文件上传失败" + oe.getMessage());
} catch (ClientException ce) {
log.error("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
log.error("Error Message:" + ce.getMessage());
throw new BusinessException("文件上传失败" + ce.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
@Override
public InputStream downloadFile(String bucketName, String objectName) throws BusinessException {
OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
try {
if (!ossClient.doesObjectExist(bucketName, objectName)) {
throw new BusinessException("文件不存在");
}
// 调用ossClient.getObject返回一个OSSObject实例,该实例包含文件内容及文件元信息。
OSSObject ossObject = ossClient.getObject(bucketName, objectName);
// 调用ossObject.getObjectContent获取文件输入流,可读取此输入流获取其内容。
InputStream content = ossObject.getObjectContent();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = content.read(buffer)) > -1) {
outputStream.write(buffer, 0, len);
}
// 数据读取完成后,获取的流必须关闭,否则会造成连接泄漏,导致请求无连接可用,程序无法正常工作。
outputStream.flush();
outputStream.close();
content.close();
return new ByteArrayInputStream(outputStream.toByteArray());
} catch (OSSException oe) {
log.error("Caught an OSSException, which means your request made it to OSS, but was rejected with an error response for some reason.");
log.error("Error Message:" + oe.getErrorMessage());
log.error("Error Code:" + oe.getErrorCode());
log.error("Request ID:" + oe.getRequestId());
log.error("Host ID:" + oe.getHostId());
throw new BusinessException("文件下载失败" + oe.getMessage());
} catch (ClientException ce) {
log.error("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
log.error("Error Message:" + ce.getMessage());
throw new BusinessException("文件下载失败" + ce.getMessage());
} catch (IOException e) {
log.error("AliYunOssServiceImpl downloadFile", e);
throw new BusinessException("文件下载失败" + e.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
private static String getContentType(String FilenameExtension) {
if (".bmp".equalsIgnoreCase(FilenameExtension)) {
return "image/bmp";
}
if (".gif".equalsIgnoreCase(FilenameExtension)) {
return "image/gif";
}
if (".jpeg".equalsIgnoreCase(FilenameExtension) ||
".jpg".equalsIgnoreCase(FilenameExtension) ||
".png".equalsIgnoreCase(FilenameExtension)) {
return "image/jpg";
}
if (".html".equalsIgnoreCase(FilenameExtension)) {
return "text/html";
}
if (".txt".equalsIgnoreCase(FilenameExtension)) {
return "text/plain";
}
if (".vsd".equalsIgnoreCase(FilenameExtension)) {
return "application/vnd.visio";
}
if (".pptx".equalsIgnoreCase(FilenameExtension) ||
".ppt".equalsIgnoreCase(FilenameExtension)) {
return "application/vnd.ms-powerpoint";
}
if (".docx".equalsIgnoreCase(FilenameExtension) ||
".doc".equalsIgnoreCase(FilenameExtension)) {
return "application/msword";
}
if (".xml".equalsIgnoreCase(FilenameExtension)) {
return "text/xml";
}
return "image/jpg";
}
}
图片压缩
package com.zft.adaptor.utils.file;
import com.zft.adaptor.utils.date.DatePattern;
import com.zft.adaptor.utils.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.UUID;
/**
* 图片压缩
*
* @author life
* Create on 2023/2/11.
*/
@Slf4j
public class CompressUtil {
public static final Integer MAX_SIZE = 200;
private static final Integer ZERO = 0;
private static final Integer ONE_ZERO_TWO_FOUR = 1024;
private static final Integer NINE_ZERO_ZERO = 900;
private static final Integer THREE_TWO_SEVEN_FIVE = 3275;
private static final Integer TWO_ZERO_FOUR_SEVEN = 2047;
private static final Double ZERO_EIGHT_FIVE = 0.85;
private static final Double ZERO_SIX = 0.6;
private static final Double ZERO_FOUR_FOUR = 0.44;
private static final Double ZERO_FOUR = 0.4;
/**
* 根据指定大小压缩图片
*
* @param imageBytes 源图片字节数组
* @param desFileSize 指定图片大小,单位kb
* @return 压缩质量后的图片字节数组
*/
public static byte[] compressPicForScale(byte[] imageBytes, long desFileSize) {
if (imageBytes == null || imageBytes.length <= ZERO || imageBytes.length < desFileSize * ONE_ZERO_TWO_FOUR) {
return imageBytes;
}
long srcSize = imageBytes.length;
double accuracy = getAccuracy(srcSize / ONE_ZERO_TWO_FOUR);
try {
while (imageBytes.length > desFileSize * ONE_ZERO_TWO_FOUR) {
ByteArrayInputStream inputStream = new ByteArrayInputStream(imageBytes);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(imageBytes.length);
Thumbnails.of(inputStream)
.scale(accuracy)
.outputQuality(accuracy)
.toOutputStream(outputStream);
imageBytes = outputStream.toByteArray();
}
log.info("图片原大小={}kb | 压缩后大小={}kb", srcSize / ONE_ZERO_TWO_FOUR, imageBytes.length / ONE_ZERO_TWO_FOUR);
} catch (Exception e) {
log.error("【图片压缩】msg=图片压缩失败!", e);
}
return imageBytes;
}
/**
* 自动调节精度(经验数值)
*
* @param size 源图片大小
* @return 图片压缩质量比
*/
private static double getAccuracy(long size) {
double accuracy;
if (size < NINE_ZERO_ZERO) {
accuracy = ZERO_EIGHT_FIVE;
} else if (size < TWO_ZERO_FOUR_SEVEN) {
accuracy = ZERO_SIX;
} else if (size < THREE_TWO_SEVEN_FIVE) {
accuracy = ZERO_FOUR_FOUR;
} else {
accuracy = ZERO_FOUR;
}
return accuracy;
}
/**
* 图片路径
*/
public static String getPath(String fileName) {
String suffix = fileName.substring(fileName.lastIndexOf("."));
return DateUtil.getNowDateString(DatePattern.PURE_DATE_PATTERN) + "/" + UUID.randomUUID() + suffix;
}
}
标签:String,objectName,com,OSS,阿里,bucketName,error,import,上传
From: https://www.cnblogs.com/ChenQ2/p/17183463.html