阿里云OSS文件存储

编程入门 行业动态 更新时间:2024-10-10 13:20:01

<a href=https://www.elefans.com/category/jswz/34/1770131.html style=阿里云OSS文件存储"/>

阿里云OSS文件存储

1、引入阿里云OSS的pom依赖

        <dependency><groupId>com.aliyun.oss</groupId><artifactId>aliyun-sdk-oss</artifactId><version>2.8.3</version></dependency><dependency><groupId>commons-fileupload</groupId><artifactId>commons-fileupload</artifactId><version>1.3.2</version></dependency>

2、配置OSS,创建 application-aliyun-oss.properties


# 文件上传大小限制
spring.servlet.multipart.max-file-size=100MB
spring.servlet.multipart.max-request-size=1000MB# 地域节点
aliyun.endPoint=oss-cn-hangzhou.aliyuncs
# Bucket 域名
aliyun.urlPrefix=LocoLoco.oss-cn-hangzhou.aliyuncs
# accessKey Id
aliyun.accessKeyId=abcdefgh
# accessKey Secret
aliyun.accessKeySecret=abcdefgh
# Bucket名称
aliyun.bucketName=LocoLoco
# 目标文件夹
aliyun.fileHost=LocoLoco

3、创建AliyunOssConfig 引入 application-aliyun-oss.properties

package com.tiktang.config;import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import lombok.Data;
import lombok.experimental.Accessors;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;/*** 阿里云oss对象存储基本配置**/
// 声明配置类,放入Spring容器
@Configuration
// 指定配置文件位置
@PropertySource(value = {"classpath:application-aliyun-oss.properties"})
// 指定配置文件中自定义属性前缀
@ConfigurationProperties(prefix = "aliyun")
@Data// lombok
@Accessors(chain = true)// 开启链式调用
public class AliyunOssConfig {private String endPoint;// 地域节点private String accessKeyId;private String accessKeySecret;private String bucketName;// OSS的Bucket名称private String urlPrefix;// Bucket 域名private String fileHost;// 目标文件夹// 将OSS 客户端交给Spring容器托管@Beanpublic OSS OSSClient() {return new OSSClient(endPoint, accessKeyId, accessKeySecret);}
}

4、上传、下载、删除

package com.tiktang.service;import cn.hutool.core.date.DateTime;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
import com.tiktang.config.AliyunOssConfig;
import com.tiktang.enums.StatusCode;
import org.apachemons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;/*** OSS文件上传,下载,删除***/
@Service("fileUploadService")
public class FileUploadService {//允许上传(图片)的格式private static final String[] IMAGE_TYPE = new String[]{".bmp", ".jpg",".jpeg", ".gif", ".png"};@Autowiredprivate OSS ossClient;   //注入阿里云oss文件服务器客户端@Autowiredprivate AliyunOssConfig aliyunOssConfig; //注入写好的阿里云oss基本配置类/*** 文件上传* 注:阿里云OSS文件上传官方文档链接:.html?spm=a2c4g.11186623.6.749.11987a7dRYVSzn* @param: uploadFile* @return: string*/public String upload(MultipartFile uploadFile) {// 获取oss的Bucket名称String bucketName = aliyunOssConfig.getBucketName();// 获取oss的地域节点String endpoint = aliyunOssConfig.getEndPoint();// 获取oss的AccessKeySecretString accessKeySecret = aliyunOssConfig.getAccessKeySecret();// 获取oss的AccessKeyIdString accessKeyId = aliyunOssConfig.getAccessKeyId();// 获取oss目标文件夹String filehost = aliyunOssConfig.getFileHost();// 返回图片上传后返回的urlString returnImgeUrl = "";// 校验图片格式boolean isLegal = false;for (String type : IMAGE_TYPE) {if (StringUtils.endsWithIgnoreCase(uploadFile.getOriginalFilename(), type)) {isLegal = true;break;}}if (!isLegal) {// 如果图片格式不合法return StatusCode.ERROR.getMsg();}// 获取文件原名称String originalFilename = uploadFile.getOriginalFilename();// 获取文件类型String fileType = originalFilename.substring(originalFilename.lastIndexOf("."));// 新文件名称String newFileName = UUID.randomUUID().toString() + fileType;// 构建日期路径, 例如:OSS目标文件夹/2021/08/03/文件名String filePath = new SimpleDateFormat("yyyy/MM/dd").format(new Date());// 文件上传的路径地址String uploadImgeUrl = filehost + "/" + filePath + "/" + newFileName;// 获取文件输入流InputStream inputStream = null;try {inputStream = uploadFile.getInputStream();} catch (IOException e) {e.printStackTrace();}/*** 下面两行代码是重点坑:* 现在阿里云OSS 默认图片上传ContentType是image/jpeg* 也就是说,获取图片链接后,图片是下载链接,而并非在线浏览链接,* 因此,这里在上传的时候要解决ContentType的问题,将其改为image/jpg*/ObjectMetadata meta = new ObjectMetadata();meta.setContentType("image/jpg");//文件上传至阿里云OSSossClient.putObject(bucketName, uploadImgeUrl, inputStream, meta);/*** 注意:在实际项目中,文件上传成功后,数据库中存储文件地址*/// 获取文件上传后的图片返回地址returnImgeUrl = "http://" + bucketName + "." + endpoint + "/" + uploadImgeUrl;return returnImgeUrl;}/*** 文件下载* @param: fileName* @param: outputStream* @return: void*/public String download(String fileName, HttpServletResponse response) throws UnsupportedEncodingException {
//        // 设置响应头为下载
//        response.setContentType("application/x-download");
//        // 设置下载的文件名
//        response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
//        response.setCharacterEncoding("UTF-8");// 文件名以附件的形式下载response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));// 获取oss的Bucket名称String bucketName = aliyunOssConfig.getBucketName();// 获取oss目标文件夹String filehost = aliyunOssConfig.getFileHost();// 日期目录// 注意,这里虽然写成这种固定获取日期目录的形式,逻辑上确实存在问题,但是实际上,filePath的日期目录应该是从数据库查询的String filePath = new DateTime().toString("yyyy/MM/dd");String fileKey = filehost + "/" + filePath + "/" + fileName;// ossObject包含文件所在的存储空间名称、文件名称、文件元信息以及一个输入流。OSSObject ossObject = ossClient.getObject(bucketName, fileKey);try {// 读取文件内容。InputStream inputStream = ossObject.getObjectContent();BufferedInputStream in = new BufferedInputStream(inputStream);// 把输入流放入缓存流ServletOutputStream outputStream = response.getOutputStream();BufferedOutputStream out = new BufferedOutputStream(outputStream);// 把输出流放入缓存流byte[] buffer = new byte[1024];int len = 0;while ((len = in.read(buffer)) != -1) {out.write(buffer, 0, len);}if (out != null) {out.flush();out.close();}if (in != null) {in.close();}return StatusCode.SUCCESS.getMsg();} catch (Exception e) {return StatusCode.ERROR.getMsg();}}/*** 文件删除* @param: objectName* @return: java.lang.String*/public String delete(String fileName) {// 获取oss的Bucket名称String bucketName = aliyunOssConfig.getBucketName();// 获取oss的地域节点String endpoint = aliyunOssConfig.getEndPoint();// 获取oss的AccessKeySecretString accessKeySecret = aliyunOssConfig.getAccessKeySecret();// 获取oss的AccessKeyIdString accessKeyId = aliyunOssConfig.getAccessKeyId();// 获取oss目标文件夹String filehost = aliyunOssConfig.getFileHost();// 日期目录// 注意,这里虽然写成这种固定获取日期目录的形式,逻辑上确实存在问题,但是实际上,filePath的日期目录应该是从数据库查询的String filePath = new DateTime().toString("yyyy/MM/dd");try {/*** 注意:在实际项目中,不需要删除OSS文件服务器中的文件,* 只需要删除数据库存储的文件路径即可!*/// 建议在方法中创建OSSClient 而不是使用@Bean注入,不然容易出现Connection pool shut downOSSClient ossClient = new OSSClient(endpoint,accessKeyId, accessKeySecret);// 根据BucketName,filetName删除文件// 删除目录中的文件,如果是最后一个文件fileoath目录会被删除。String fileKey = filehost + "/" + filePath + "/" + fileName;ossClient.deleteObject(bucketName, fileKey);try {} finally {ossClient.shutdown();}System.out.println("文件删除!");return StatusCode.SUCCESS.getMsg();} catch (Exception e) {e.printStackTrace();return StatusCode.ERROR.getMsg();}}}

5、调用阿里云OSS的service,书写controller

    @PostMapping("updateLogo")public Result upload(@RequestParam("file") MultipartFile file) {if (file != null) {String returnFileUrl = fileUploadService.upload(file);if (returnFileUrl.equals("error")) {return Result.error().message("头像上传失败!");}return Result.ok().data("FileUrl",returnFileUrl);} else {return Result.error().message("头像上传失败!");}}

6、实例,修改用户头像

    @PostMapping("/updateUserImg")public Result updateUserImg(@RequestParam MultipartFile file,@RequestParam String token){if (file != null) {String returnFileUrl = fileUploadService.upload(file);if (returnFileUrl.equals("error")) {return Result.error().message("头像修改失败!");}User user1 = userService.findUserByToken(token);String u_tel = user1.getUTel();QueryWrapper<User> queryWrapper = new QueryWrapper<>();queryWrapper.eq("u_tel",u_tel);User user = userMapper.selectOne(queryWrapper);user.setUImgUrl(returnFileUrl);userMapper.updateById(user);String json = JSON.toJSONString(user);stringRedisTemplate.opsForValue().set("TOKEN_"+token, json, Duration.ofDays(1));return Result.ok().message("头像修改成功");} else {return Result.error().message("头像修改失败!");}}

7、postman测试

更多推荐

阿里云OSS文件存储

本文发布于:2024-03-10 08:57:58,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1727532.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:阿里   文件   OSS

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!