1:常用的图片服务器
- hdfs
- fastdfs
- oss
2:OSS
- 通过阿里云实现存储对象来管理文件
注册阿里云
https://oss.console.aliyun.com
开通oss服务
创建bucket
复制外网的endpoint
创建公钥
oss-cn-beijing.aliyuncs.com | java40.oss-cn-beijing.aliyuncs.com | |
---|---|---|
java40 |
外网访问 | 支持 | oss-cn-beijing.aliyuncs.com | java43-zhiyou.oss-cn-beijing.aliyuncs.com |
---|---|---|---|
AccessKey ID xxxxxxxxxxx
AccessKey Secret xxxxxxxxxxxxxx
复制公钥的id和secret
aliyun.oss.file.keyid=xxxxxxxxxx
aliyun.oss.file.keysecret=xxxxxxxxxxxx
创建springboot项目
- 导入jar报
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.zhiyou100.springcloud</groupId>
<artifactId>test34_oss</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>test34_oss</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- 阿里云oss依赖 -->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.8.0</version>
</dependency>
<!-- 日期工具栏依赖 -->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.10.10</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
- 创建实体类:名字随意记录oss需要的所有属性
package com.zhiyou100.entity;
import lombok.*;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Component
@ConfigurationProperties(prefix = "aliyun.oss.file")
public class ConstantPropertiesUtils{
private String endpoint;
private String keyid;
private String keysecret;
private String bucketname;
}
- 注解报错:添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
- 在配置文件中创建aliyun.oss.file前缀的相关属性
#前缀自己定义 但一定要统一和ConfigurationProperties的prefix一致即可
aliyun.oss.file.bucketname=springcloud-java34
aliyun.oss.file.endpoint=oss-cn-beijing.aliyuncs.com
aliyun.oss.file.keyid=LTAI5tE6gfKNuyiUpunks2qx
aliyun.oss.file.keysecret=sHQGu3angXYH5mhbJSK8dDismMxema
- 创建service
package com.zhiyou100.service;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.GetObjectRequest;
import com.zhiyou100.entity.ConstantPropertiesUtils;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.io.File;
import java.io.InputStream;
import java.util.UUID;
@Service
@Slf4j
public class OssService{
@Resource
private ConstantPropertiesUtils constantPropertiesUtils;
public String uploadFileAvatar(MultipartFile file) {
//获取oss上传配置文件中的参数
String bucketName = constantPropertiesUtils.getBucketname();
String endpoint = constantPropertiesUtils.getEndpoint();
String keyId = constantPropertiesUtils.getKeyid();
String keySecret = constantPropertiesUtils.getKeysecret();
OSS ossClient;
InputStream inputStream;
try {
// 创建OSSClient实例。
ossClient = new OSSClientBuilder().build(endpoint, keyId, keySecret);
// 上传文件流
inputStream = file.getInputStream();
//为了使得文件可以重复上传,每次上传的时候需要将文件名进行修改
String fileName = file.getOriginalFilename();
log.info("图片上传的名字为:{}",fileName);
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
String newFileName = uuid + fileName;
//获取当前日期,然后以日期和新的文件名组成全路径,使得oss中的文件按照日期进行分类存储
String date = new DateTime().toString("yyyy/MM/dd");
String fullFileName = date + "/" + newFileName;
log.info("图片保存在oss的全路径为:{}",fullFileName);
//第一个参数Bucket名称 第二个参数 上传到oss文件路径和文件名称
ossClient.putObject(bucketName, fullFileName, inputStream);
// 关闭OSSClient。
ossClient.shutdown();
return "https://"+bucketName+"."+ endpoint+"/"+fullFileName;
} catch (Exception e) {
log.error("文件上传失败",e);
throw new RuntimeException("文件上传oss失败");
}
}
public void downLoadFileAvatar(String yuan, File muDi) {
//获取oss上传配置文件中的参数
String bucketName = constantPropertiesUtils.getBucketname();
String endpoint = constantPropertiesUtils.getEndpoint();
String keyId = constantPropertiesUtils.getKeyid();
String keySecret = constantPropertiesUtils.getKeysecret();
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, keyId, keySecret);
// 下载Object到本地文件,并保存到指定的本地路径中。如果指定的本地文件存在会覆盖,不存在则新建。
// 如果未指定本地路径,则下载后的文件默认保存到示例程序所属项目对应本地路径中。
File muDiFile=new File(muDi,System.currentTimeMillis()+(yuan.substring(yuan.indexOf("."))));
ossClient.getObject(new GetObjectRequest(bucketName, yuan),muDiFile);
// 关闭OSSClient。
ossClient.shutdown();
}
}
- action
package com.zhiyou100.controller;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.GetObjectRequest;
import com.zhiyou100.service.OssService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.io.File;
import java.util.HashMap;
@RestController
@RequestMapping("/eduoss")
@CrossOrigin
public class OssController {
@Resource
private OssService ossService;
//上传头像的方法
@PostMapping("/upload")
public String uploadOssFile(MultipartFile file) {
String url = ossService.uploadFileAvatar(file);
HashMap<String, String> map = new HashMap<>();
map.put("url",url);
return map+"上传成功!";
}
@GetMapping("/download")
public String downloadFile(String fileName){
File muDiDir=new File("d:/oss");
ossService.downLoadFileAvatar(fileName,muDiDir);
return "下载完毕!";
}
}
测试
通过postman测试:文件上传
通过postman测试:文件下载