阿里云OSS图片上传压缩
pom文件增加图片压缩依赖包
<!-- 图片压缩 -->
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.8</version>
</dependency>
<!-- 阿里云对象存储 -->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>2.8.3</version>
</dependency>
增加图片上传工具类SysOSSUplodFile.java
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.img.Img;
import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.aliyun.oss.*;
import com.aliyun.oss.model.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhc.gds.common.core.constant.CommonConstants;
import com.zhc.gds.common.utils.ImageUtil;
import com.zhc.gds.common.utils.MagicalValueConstants;
import com.zhc.gds.common.utils.R;
import com.zhc.gds.entity.upms.SysFile;
import com.zhc.gds.mapper.upms.SysFileMapper;
import com.zhc.gds.service.upms.HttpSessionService;
import com.zhc.gds.service.upms.SysFileService;
import com.zhc.gds.service.upms.SysPublicParamService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.time.LocalDate;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 文件管理
*
* @author Luckly
* @date 2019-06-18 17:18:42
*/
@Slf4j
@Service
public class SysFileServiceImpl extends ServiceImpl<SysFileMapper, SysFile> implements SysFileService {
/*阿里云oss上传文件方式*/
//你的oss所在域,要加http:// 不明白可以对照你的文件引用地址
@Value("${aliyun.oss.endpoint}")
private String endpoint;
//密匙keyId 可以在阿里云获取到
@Value("${aliyun.oss.accessKeyId}")
private String accessKeyId;
//密匙keySecret 可以在阿里云获取到
@Value("${aliyun.oss.accessKeySecret}")
private String accessKeySecret;
//你的bucketName存储桶 名称 即是你的OSS对象名称 不明白查oss开发文档专业术语
@Value("${aliyun.oss.bucketName}")
private String bucketName;
/*
* 以下是常量,按照阿里代码开发规范,不允许代码中出现魔法值
*/
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 file
* @return
*/
@Override
public R uploadFile(MultipartFile file) {
String fileName = IdUtil.simpleUUID() + StrUtil.DOT + FileUtil.extName(file.getOriginalFilename());
String allName = this.getNowYearMonthDay() + "/" + fileName;
Map<String, String> resultMap = new HashMap<>(4);
resultMap.put("name", file.getOriginalFilename());
resultMap.put("bucketName", bucketName);
resultMap.put("fileName", allName);
//上传成功后获取文件路径
String previewUrl = publicParamService.getSysPublicParamKeyToValue("MINIO_IMAGE_PREVIEW_URL");
resultMap.put("url", url);
// 写入文件
try {
//获取上传的输入流
InputStream inputStream = file.getInputStream();
//获取图片类型
String contentType = getContentType(fileName.substring(fileName.lastIndexOf(".")));
//设置访问地址是默认是预览图片
ObjectMetadata meta = new ObjectMetadata();
/**
* 下面两行代码是重点坑:
* 现在阿里云OSS 默认图片上传ContentType是image/jpeg
* 也就是说,获取图片链接后,图片是下载链接,而并非在线浏览链接,
* 因此,这里在上传的时候要解决ContentType的问题,将其改为image/jpg
*/
meta.setCacheControl("no-cache");
meta.setContentType(contentType);
meta.setHeader("Pragma", "no-cache");
// 创建OSSClient实例
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
/*
调用oss上传到阿里云对象存储oss----Bucket存储空间
第一个参数 bucket名称
第二个参数 文件名称
第三个参数 输入流
第四个参数 文件类型
*/
if (!ossClient.doesBucketExist(bucketName)) {
//创建bucket
ossClient.createBucket(bucketName);
//设置oss实例的访问权限:公共读
ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
}
//文件上传至阿里云
String extName = FileUtil.extName(file.getOriginalFilename());
if(StrUtil.isNotBlank(extName)){
extName = extName.toLowerCase();
}
if(extName.contains("gif") || extName.contains("jpg") || extName.contains("bmp")|| extName.contains("png")|| extName.contains("jpeg")){
byte[] bytes = file.getBytes();
//调用图片压缩方法,这里压缩到100k左右
bytes = compressPicForScale(bytes,100);
InputStream sbs = new ByteArrayInputStream(bytes);
meta.setContentLength(bytes.length);
ossClient.putObject(bucketName, allName, sbs, meta);
}else{
ossClient.putObject(bucketName, allName, inputStream, meta);
}
// 关闭OSSClient。
ossClient.shutdown();
// 文件管理数据记录,收集管理追踪文件
fileLog(file, resultMap.getOrDefault("url", fileName));
} catch (IOException e) {
log.error("上传失败", e);
return R.failed(e.getLocalizedMessage());
}
return R.ok(resultMap);