阿里云 OSS 云存储 文件上传
文章目录
- 人生格言
- 阿里云 oss
- 开通对象存储 oss
- 阿里运 oss管理控制台的使用
- java 代码操作阿里云 oss
- service_oss模块
- 实现二进制文件的上传
- 在阿里云开通 对象存储服务 oss
- 创建 bucket
- 创建 许可证
- 在pom中引入依赖
- 编写配置文件
- 编写controller
- 编写service
- 编写serviceimpl
- 测试
- 测试结果
- 解决以下问题
- 产生不同的文件名
- 实现文件的分类存储
人生格言
未来犹存,人生当前
阿里云 oss
开通对象存储 oss
阿里运 oss管理控制台的使用
java 代码操作阿里云 oss
service_oss模块
实现二进制文件的上传
在阿里云开通 对象存储服务 oss
创建 bucket
创建 许可证
点击用户头像
在pom中引入依赖
<dependency><groupId>com.aliyun.oss</groupId><artifactId>aliyun-sdk-oss</artifactId><version>3.10.2</version>
</dependency><!-- 阿里云oss依赖 --><dependency><groupId>com.aliyun.oss</groupId><artifactId>aliyun-sdk-oss</artifactId></dependency><!--日期工具栏依赖--><dependency><groupId>joda-time</groupId><artifactId>joda-time</artifactId></dependency>
编写配置文件
#服务端口
server.port=8002
#服务名
spring.application.name=service-oss
#环境设置:dev、test、prod
spring.profiles.active=dev
#阿里云 OSS
#不同的服务器,地址不同
aliyun.oss.file.endpoint=
aliyun.oss.file.keyid=
aliyun.oss.file.keysecret=
#bucket可以在控制台创建,也可以使用java代码创建
aliyun.oss.file.bucketname=
// yourEndpoint填写自定义域名。
String endpoint = "yourEndpoint";
// 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
String accessKeyId = "yourAccessKeyId";
String accessKeySecret = "yourAccessKeySecret";
编写controller
package com.gsx.ossservice.controller;import com.gsx.commonUtils.Result;
import com.gsx.ossservice.service.OssService;
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("/eduoss/fileoss")
@CrossOrigin
public class OssController {@Autowiredprivate OssService ossService;//上传头像的方法@PostMappingpublic Result uploadOssFile(MultipartFile file){//获取上传文件 MultipartFile//返回上传到oss的路径String url =ossService.uploadFileAvatar(file);return Result.success().data("url",url);}}
编写service
package com.gsx.ossservice.service;import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;public interface OssService {String uploadFileAvatar(MultipartFile file);
}
编写serviceimpl
package com.gsx.ossservice.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 {//常量类,读取配置文件application.properties中的配置@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 KEY_ID;public static String KEY_SECRET;public static String BUCKET_NAME;@Overridepublic void afterPropertiesSet() throws Exception {KEY_ID=this.keyid;KEY_SECRET=this.keysecret;END_POINT=this.endpoint;BUCKET_NAME=this.bucketname;}
}
package com.gsx.ossservice.service.impl;import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.gsx.ossservice.service.OssService;
import com.gsx.ossservice.utils.ConstantPropertiesUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;import java.io.IOException;
import java.io.InputStream;@Service
public class OssServiceImpl implements OssService {@Overridepublic String uploadFileAvatar(MultipartFile file) {//工具类获取值String endpoint = ConstantPropertiesUtils.END_POINT;String accessKeyId = ConstantPropertiesUtils.KEY_ID;String accessKeySecret = ConstantPropertiesUtils.KEY_SECRET;String bucketName = ConstantPropertiesUtils.BUCKET_NAME;InputStream inputStream = null;try {// 创建OSS实例。OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);// 获取上传文件的输入流inputStream = file.getInputStream();//获取文件名称String fileName = file.getOriginalFilename();//调用oss实例中的方法实现上传//参数1: Bucket名称//参数2: 上传到oss文件路径和文件名称 /aa/bb/1.jpg//参数3: 上传文件的输入流ossClient.putObject(bucketName, fileName, inputStream);// 关闭OSSClient。ossClient.shutdown();//把上传后文件路径返回//需要把上传到阿里云oss路径手动拼接出来//https://achang-edu.oss-cn-hangzhou.aliyuncs.com/default.gifString url = "http://"+bucketName+"."+endpoint+"/"+fileName ;return url;} catch (IOException e) {e.printStackTrace();return null;}}
}
官方参考
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import java.io.FileInputStream;
import java.io.InputStream;public class Demo {public static void main(String[] args) throws Exception {// Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";// 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。String accessKeyId = "yourAccessKeyId";String accessKeySecret = "yourAccessKeySecret";// 填写Bucket名称,例如examplebucket。String bucketName = "examplebucket";// 填写Object完整路径,完整路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。String objectName = "exampledir/exampleobject.txt";// 填写本地文件的完整路径,例如D:\\localpath\\examplefile.txt。// 如果未指定本地路径,则默认从示例程序所属项目对应本地路径中上传文件流。String filePath= "D:\\localpath\\examplefile.txt";// 创建OSSClient实例。OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);try {InputStream inputStream = new FileInputStream(filePath); // 创建PutObject请求。ossClient.putObject(bucketName, objectName, inputStream);} catch (OSSException oe) {System.out.println("Caught an OSSException, which means your request made it to OSS, "+ "but was rejected with an error response for some reason.");System.out.println("Error Message:" + oe.getErrorMessage());System.out.println("Error Code:" + oe.getErrorCode());System.out.println("Request ID:" + oe.getRequestId());System.out.println("Host ID:" + oe.getHostId());} catch (ClientException ce) {System.out.println("Caught an ClientException, which means the client encountered "+ "a serious internal problem while trying to communicate with OSS, "+ "such as not being able to access the network.");System.out.println("Error Message:" + ce.getMessage());} finally {if (ossClient != null) {ossClient.shutdown();}}}
}
测试
测试结果
解决以下问题
产生不同的文件名
//获取文件名称String fileName = file.getOriginalFilename();//在文件名称里面添加随机惟一的值String uuid = UUID.randomUUID().toString().replaceAll("-","");//fileName 和 uuid 做拼接确保文件名称唯一fileName=uuid+fileName;
实现文件的分类存储
//把文件按照日期进行分类//获取当前的日期 使用工具类String datePath= new DateTime().toString("yyyy/MM/dd");//拼接 2022/5/4/filenamefileName=datePath+"/"+fileName;
阿里云 OSS 云存储 文件上传相关推荐
- 微信头像下载并上传到阿里云OSS,PHP文件上传到阿里云OSS简单代码(OSS文件上传,微信头像下载,CURL下载文件,微信头像链接过期)
(就这么个小事,有多少公司多少项目没做到!!) 微信公众号项目,后端获取到授权用户的微信头像后,要自行下载保存,不下载的话,微信返回的头像链接会在一段时间后过期,无法访问! 下面是我写的两个简单实用方 ...
- SpringBoot整合阿里云OSS,支持文件上传、下载、删除、加签等操作
首先附上OSS基本介绍和官方文档链接:https://help.aliyun.com/product/31815.html?spm=ata.21736010.0.0.25d67536bR4cly 另外 ...
- 阿里云OSS直传多文件上传遇到的问题及解决方案
本人萌新,刚实习不久,在上一个项目需求中,需要用到阿里云的文件直传服务,通过各种找,最终找了一个比较靠谱的demo,基于plupload插件的一个前端文件上传插件.然后自己再进行了二次封装,并对其中的 ...
- 阿里云OSS对象存储 , js 上传文件
function uploadFile2(){// 上传后的文件路径和文件名var fileName = "20220420/使用ajax上传图片.jpg";// 获取oss上传令 ...
- 阿里云oss简单的文件上传步骤
1.登录阿里云然后点击开通 2.同意协议点击开通 3.创建存储容器 4.导入maven坐标 <dependency><groupId>com.aliyun.oss</gr ...
- 阿里云OSS对象存储服务上传失败问题之一
简介: OSS是阿里云提供一个对象存储服务,有着稳定高效的特点,但在操作时有些问题还是必须要注意一下的 今天在进行上传头像的操作时,发生了一个OSS连接时出现的问题,导致头像上传失败,问题的样式如下图 ...
- python程序发布到阿里云云服务器_Python实现阿里云服务器里的文件上传与下载
Python实现阿里云服务器里的文件上传与下载 018.4.15 背景: 老实说,因为现实的各种原因造成电脑换来换去是可能出现的事情,但是电脑能换,电脑里的环境却不能换.我就曾在三个电脑里各自安装了虚 ...
- PHP上传图片文件到又拍云,如何把文件上传到又拍云
PHP上传图片文件到又拍云,如何把文件上传到又拍云: https://www.tpxhm.com/adetail/593.html
- 阿里云oss权限控制,上传下载测试
2019独角兽企业重金招聘Python工程师标准>>> 列子公共读: 新建一个bucket - > data 存储目录 新建读写账号 -> 访问控制RAM -> 权 ...
- vue直传图片到阿里云OSS(单张直接上传)
背景: 近期项目使用到多图片上传功能,常规的调用后端接口上传,可能会出现上传速度慢,体验不佳的情况.那么就考虑另一种上传方式.由前端直接上传到oss.快的一匹... 经过摸索,也实现了.代码其实没啥难 ...
最新文章
- 倒计时 3 天!「2019 嵌入式智能国际大会」全日程大公开!
- Typescript 基本类型
- 微型计算机技术怎么学,浅谈微型计算机技术课程的启发式教学
- 他读博期间发表3篇Science,28岁任武大教授,35岁入“杰青”名单,让人叹服!...
- 华为云PB级数据库GaussDB(for Redis)揭秘第六期:Feed流场景中的应用
- java string能存储多长_String 有多长?
- 数据库读写锁的C++实现
- ajax返回值demo
- 大屏数据可视化效果如何提升
- 在线阅读各版本android系统源代码
- 支付宝小程序唤起支付
- 微信\支付宝扫码条码区分规则
- OpenGl运行窗口出现纯白色
- 回顾计算机发展史:速度惊人_升级并发布:第24周回顾
- 修真院教学模式三大阶段之真实项目
- MS-DOS系统下的autoexec.bat
- python-re模块-hashlib模块
- 域名该怎样选_网站域名应该怎样选择?
- window hello指纹设置不了,弹窗闪退。
- 素数的通项公式是什么