Springboot整合阿里云OSS上传图片
第一步: 准备
aliyun.access-id=自己的
aliyun.access-key=自己的
aliyun.bucket=自己的
aliyun.endpoint=自己的
aliyun.dir=自己的
第二步:导入阿里OSS的依赖
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.5.0</version>
</dependency>
第三步:创建 allyun.properties
aliyun.access-id=LTAI4FkSy78FtxJEGSYMzEVk
aliyun.access-key=vXrfuwNhH2McGkaJQVUXzhoN1r8BpL
aliyun.bucket=bj-yys
aliyun.endpoint=oss-cn-beijing.aliyuncs.com
aliyun.dir=bj-yys/
第四步: OSS工具类
下面展示 OSS工具类代码
。
@Component
@PropertySource("classpath:/allyun.properties")
public class OSSProperties implements InitializingBean {
@Value("${aliyun.endpoint}")
private String aliyun_endpoint;
@Value("${aliyun.access-id}")
private String aliyun_access_id;
@Value("${aliyun.access-key}")
private String aliyun_access_key;
@Value("${aliyun.bucket}")
private String aliyun_bucket;
@Value("${aliyun.dir}")
private String aliyun_dir;
//声明静态变量,
public static String ALIYUN_ENDPOINT ;
public static String ALIYUN_ACCESS_ID ;
public static String ALIYUN_ACCESS_KEY ;
public static String ALIYUN_BUCKET ;
public static String ALIYUN_DIR ;
@Override
public void afterPropertiesSet() throws Exception {
ALIYUN_ENDPOINT = aliyun_endpoint;
ALIYUN_ACCESS_ID = aliyun_access_id;
ALIYUN_ACCESS_KEY = aliyun_access_key;
ALIYUN_BUCKET = aliyun_bucket;
ALIYUN_DIR = aliyun_dir;
}
}
第五步:上传图片
OSS工具类
下面展示 OSS工具类
。
public class OSSUtil {
/**
* log日志
*/
public static final Logger logger = LoggerFactory.getLogger(OSSUtil.class);
private String endpoint= OSSProperties.ALIYUN_ENDPOINT;
private String accessKeyId=OSSProperties.ALIYUN_ACCESS_ID;
private String accessKeySecret=OSSProperties.ALIYUN_ACCESS_KEY;
private String bucketName=OSSProperties.ALIYUN_BUCKET;
private String FOLDER=OSSProperties.ALIYUN_DIR;
/**
* 上传图片
*
* @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(MultipartFile file) throws IOException {
/* if (file.getSize() > 10 * 1024 * 1024) {
throw new IOException("上传图片大小不能超过10M!");
}*/
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 IOException("图片上传失败");
}
}
/**
* 获得图片路径
*
* @param fileUrl
* @return
*/
public String getImgUrl(String fileUrl) {
System.out.println(fileUrl);
if (!StringUtils.isEmpty(fileUrl)) {
String[] split = fileUrl.split("/");
return this.getUrl(this.FOLDER + split[split.length - 1]);
}
return "" ;
}
/**
* 上传到OSS服务器 如果同名文件会覆盖服务器上的
*
* @param instream
* 文件流
* @param fileName
* 文件名称 包括后缀名
* @return 出错返回"" ,唯一MD5数字签名
*/
public String uploadFile2OSS(InputStream instream, String fileName) {
String ret = "";
try {
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
// 创建上传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, FOLDER + fileName, instream, objectMetadata);
ret = putResult.getETag();
} catch (IOException e) {
logger.error(e.getMessage(), e);
} finally {
try {
if (instream !=null ) {
instream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return ret;
}
/**
* Description: 判断OSS服务文件上传时文件的contentType
*/
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";
}
/**
* 获得url链接
*
* @param key
* @return
*/
public String getUrl(String key) {
// 设置URL过期时间为10年 3600l* 1000*24*365*10
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10);
// 生成URL
URL url = ossClient.generatePresignedUrl(bucketName, key, expiration);
/* url = "https://" + bucketName + ".oss-cn-beijing.aliyuncs.com/" + bucketName+"/"+ key;*/
if (url != null) {
String host ="https://"+url.getHost()+url.getPath();
return host;
}
return "";
}
}
Controller层方法
上传图片
public Map<String,Object> uploadPhoto(@RequestParam("imgFile") MultipartFile imgFile,HttpServletRequest req) throws Exception {
OSSUtil ossClient=new OSSUtil();
Map<String, Object> m = new HashMap<>();
if (imgFile.isEmpty()) {
m.put("error","上传文件不能为空");
}
String newsUrl = "";
if (!((MultipartFile) imgFile).isEmpty()) {
try {
//将文件上传
String name = ossClient.uploadImg2Oss(imgFile);
//获取文件的URl地址 以便前台 显示
String imgUrl = ossClient.getImgUrl(name);
m.put("url",imgUrl);
} catch (IOException e) {
e.printStackTrace();
}
}else {
m.put("error","上传图片不可为空");
}
return m;
}