使用AliyunOSS实现图片上传功能并且判断文件格式和内容是否正确
一、新建一个springboot项目:guan_oss
二、在pom.xml中增加依赖
<dependencies>
<!--aliyunOSS-->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>2.8.3</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
三、application.properties
#阿里云 OSS
#不同的服务器,地址不同
aliyun.oss.file.endpoint=oss-cn-shanghai.aliyuncs.com
aliyun.oss.file.keyid=xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
aliyun.oss.file.keysecret=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
#bucket可以在控制台创建,也可以使用java代码创建
aliyun.oss.file.bucketname=xxxxxxxxxxxxxxxxxxxxxxx
四、新建ConstantPropertiesUtil类
实现InitializingBean
用spring的 InitializingBean 的 afterPropertiesSet 来初始化配置信息,这个方法将在所有的属性被初始化后调用。
@Component
public class ConstantPropertiesUtil 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.filehost}")
private String fileHost;
@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;
public static String FILE_HOST ;
@Override
public void afterPropertiesSet() throws Exception {
END_POINT = endpoint;
ACCESS_KEY_ID = keyId;
ACCESS_KEY_SECRET = keySecret;
BUCKET_NAME = bucketName;
FILE_HOST = fileHost;
}
}
五、创建Service接口
public interface FileService {
/**
* 上传文件接口
* 返回url
*/
String upload(MultipartFile file);
}
六、参考阿里云OSS的SDK完成实现类
@Service
public class FileServiceImpl implements FileService {
//定义允许上传的文件格式
private static String TYPESTR[] = {".png",".jpg",".gif",".bmp",".jpeg"};
@Override
public String upload(MultipartFile file) {
OSSClient ossClient = null;
String url = null;
try {
// 创建OSSClient实例。
ossClient = new OSSClient(ConstantPropertiesUtil.END_POINT,
ConstantPropertiesUtil.ACCESS_KEY_ID,
ConstantPropertiesUtil.ACCESS_KEY_SECRET);
//判断文件格式
boolean flag = false;
for (String type : TYPESTR) {
if (StringUtils.endsWithIgnoreCase(file.getOriginalFilename(),type)){
flag = true;
break;
}
}
if (!flag) {
return "图片格式不正确";
}
//判断文件内容
BufferedImage image = ImageIO.read(file.getInputStream());
if (image != null) {
System.err.println(String.valueOf(image.getHeight()));
System.err.println(String.valueOf(image.getWidth()));
}else {
return "文件内容不正确";
}
//获取文件名
String filename = file.getOriginalFilename();
String ext = filename.substring(filename.lastIndexOf("."));
String newName = UUID.randomUUID().toString().replaceAll("-","")+ext;
String datePath = new DateTime().toString("yyyy/MM/dd");
String urlPath = ConstantPropertiesUtil.FILE_HOST+"/"+datePath+"/"+newName;
// 上传文件流。
InputStream inputStream = file.getInputStream();
ossClient.putObject(ConstantPropertiesUtil.BUCKET_NAME, urlPath, inputStream);
url = "https://"+ConstantPropertiesUtil.BUCKET_NAME+"."+ConstantPropertiesUtil.END_POINT+"/"+urlPath;
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭OSSClient。
ossClient.shutdown();
}
return url;
}
}
七、创建Controller
@RestController
@RequestMapping("/oss")
@CrossOrigin //解决跨域问题
public class FileController {
@Autowired
FileService fileService;
/**
* 上传文件
*
*/
@PostMapping("/file/upload")
public String upload(MultipartFile file) {
//调用oss上传
String url = fileService.upload(file);
return url;
}
八、配置Swagger
@EnableSwagger2
@Configuration
public class AppSwaggerConfig {
}
九、在Swagger中测试
评论区