思路:前端访问上传接口,传本地图片,后端根据图片调用工具类把图片上传到阿里云,返回一个服务器上图片的下载链接给前端。
一、普通上传
public class OssTest {
public static void main(String[] args) throws FileNotFoundException {
// 区域
String endpoint = "http://oss-cn-beijing.aliyuncs.com";
// 秘钥
String accessKeyId = "LTAI5tPwAwJxRP6utEp6sRZE";
String accessKeySecret = "qcI7xgSb3KKpf42SFrqq5q2E8IDv8x";
// 存储空间
String bucketName = "tlias-web-management-mfc";
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
// 上传文件
InputStream inputStream = new FileInputStream("C:\\Users\\sion\\Desktop\\证件照片\\2f799673839e1e7bf86848a86931561.jpg");
//参数1: 桶名字 参数2: 图片上传后名字 参数3: 图片流
ossClient.putObject(bucketName, "证件照.jpg", inputStream);
// 关闭OSSClient。
ossClient.shutdown();
}
}
二、模板上传
- 配置文件
aliyun:
oss:
endpoint: oss-cn-beijing.aliyuncs.com
accessKeyId: LTAI5tPwAwJxRP6utEp6sRZE
accessKeySecret: qcI7xgSb3KKpf42SFrqq5q2E8IDv8x
bucketName: tlias-web-management-mfc
url: https://tlias-web-management-mfc.oss-cn-beijing.aliyuncs.com
2.配置类
@Data
@Component
@ConfigurationProperties(prefix = "aliyun.oss") //读取配置文件
public class OssProperties {
//服务器区域
private String endpoint;
//密匙key
private String accessKeyId;
//密匙
private String accessKeySecret;
//存储空间
private String bucketName;
//域名
private String url;
}
- OssTemplate工具类
//阿里存储工具类
@Component
public class OssTemplate {
//注入配置参数实体类对象
@Autowired
private OssProperties ossProperties;
//文件上传
public String upload(String fileName, InputStream inputStream) {
//创建客户端
OSS ossClient = new OSSClientBuilder().build(ossProperties.getEndpoint(),
ossProperties.getAccessKeyId(), ossProperties.getAccessKeySecret());
//设置文件最终的路径和名称
String objectName = "images/" + new SimpleDateFormat("yyyy/MM/dd").format(new Date())
+ "/" + System.currentTimeMillis() + fileName.substring(fileName.lastIndexOf("."));
//meta设置请求头,解决访问图片地址直接下载
ObjectMetadata meta = new ObjectMetadata();
meta.setContentType(getContentType(fileName.substring(fileName.lastIndexOf("."))));
//上传
ossClient.putObject(ossProperties.getBucketName(), objectName, inputStream, meta);
//关闭客户端
ossClient.shutdown();
return ossProperties.getUrl() + "/" + objectName;
}
//文件后缀处理
private 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";
}
return "image/jpg";
}
}
2.controller层
@Slf4j
@RestController
public class FileController {
@Autowired
OssTemplate ossTemplate;
@PostMapping("/upload")
//MultipartFile :接收文件类型
public Result uploadFile(MultipartFile image) throws IOException {
//调用文件上传
String filePath = ossTemplate.upload(image.getOriginalFilename(),image.getInputStream());
log.info("服务器文件路径:" + filePath);
//返回文件路径
return Result.success(filePath);
}
}