阿里OSS实现图片上传,返回预览地址
注册阿里OSS
首先进入阿里云的官网:https://www.aliyun.com/
紧接着点击首页上的立即开通: 点击这个创建一个bucket
其余的默认就可以,可以根据自己的实际需求去写
使用代码操作阿里OSS
首先需要申请一个阿里颁发(id和秘钥) 在控制台的这里进入: 去创建一个AccessKey 创建完成之后就科一开始配置java了
Spring Boot 初始化OSS
阿里OSS开发文档地址:https://help.aliyun.com/document_detail/32008.html 首先在pom文件中添加依赖:
<!-- 阿里 oss 存储 -->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.10.2</version>
</dependency>
这个大家可以参考官方文档 JDK9以上需要添加别的依赖,我这里是JDK8
紧接着在application.yml中配置阿里OSS的秘钥
aliyun:
oss:
file:
endpoint: https://阿里云地址.com
keyid:
keysecret:
bucketname:
配置完成之后编写配置类
package com.an.notepad.utils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class ConstantPropertiesUtils implements InitializingBean {
@Value("${aliyun.oss.file.endpoint}")
private String endpoint;
@Value("${aliyun.oss.file.keyid}")
private String keyId;
@Value("${aliyun.oss.file.keysecret}")
private String keySecret;
@Value("${aliyun.oss.file.bucketname}")
private String bucketName;
public static String END_POINT;
public static String ACCESS_KEY_ID;
public static String ACCESS_KEY_SECRET;
public static String BUCKET_NAME;
@Override
public void afterPropertiesSet() throws Exception {
END_POINT = endpoint;
ACCESS_KEY_ID = keyId;
ACCESS_KEY_SECRET = keySecret;
BUCKET_NAME = bucketName;
}
}
上传图片和删除图片的controller层
package com.an.notepad.controller;
import com.an.notepad.common.Result;
import com.an.notepad.service.OssService;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
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;
@RestController
@RequestMapping("/images")
@CrossOrigin
public class OssController {
@Autowired
private OssService ossService;
@ApiOperation(value = "上传图片")
@RequiresAuthentication
@PostMapping("/upload")
public Result uploadImages(MultipartFile file) {
String url = ossService.uploadImages(file);
return Result.succ(url);
}
@ApiOperation(value = "删除图片")
@RequiresAuthentication
@PostMapping("/delete")
public Result deleteImages(String fileUrl) {
boolean flag = ossService.deleteImages(fileUrl);
if (flag) {
return Result.succ("删除成功", true);
}
return Result.fail("删除失败", false);
}
}
下面是Service层:
package com.an.notepad.service;
import org.springframework.web.multipart.MultipartFile;
public interface OssService {
String uploadImages(MultipartFile file);
boolean deleteImages(String fileUrl);
}
紧接着是实现层:(主要的核心逻辑就在这里面了,具体代码意思可以看注释)
package com.an.notepad.service.impl;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
import com.an.notepad.service.OssService;
import com.an.notepad.utils.ConstantPropertiesUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.ByteArrayInputStream;
import java.util.Date;
@Service
public class OssServiceImpl implements OssService {
@Override
public String uploadImages(MultipartFile file) {
String endpoint = ConstantPropertiesUtils.END_POINT;
String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;
String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET;
String bucketName = ConstantPropertiesUtils.BUCKET_NAME;
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
try {
String fileName = file.getOriginalFilename();
ObjectMetadata objectMetadata = new ObjectMetadata();
objectMetadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf("."))));
ossClient.putObject(bucketName, fileName, new ByteArrayInputStream(file.getBytes()),objectMetadata);
ossClient.shutdown();
Date expiration = new Date(System.currentTimeMillis() + 946080000 * 1000);
String url = ossClient.generatePresignedUrl(bucketName, fileName, expiration).toString();
return url;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
@Override
public boolean deleteImages(String fileUrl) {
String endpoint = ConstantPropertiesUtils.END_POINT;
String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;
String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET;
String bucketName = ConstantPropertiesUtils.BUCKET_NAME;
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
String imgFile = fileUrl.replace("https://bucket-ans.oss-cn-hangzhou.aliyuncs.com/", "");
String fileName = imgFile.substring(0, imgFile.indexOf("?"));
ossClient.deleteObject(bucketName, fileName);
ossClient.shutdown();
return true;
}
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/jpg";
}
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/jpg";
}
}
这样的话后端的接口就做好了
我这里项目集成了swagger2所以我用swagger接口文档进行测试: 预览成功 这种方式还是相对比较简单的。
|