一、同阿里产品,云服务器和存储对象oss-配置内网访问
阿里存储对象oss 地址: https://oss./overview
配置须知
通过Nginx 进行网络转发,安装Nginx 教程: /qq_41463655/article/details/100580572
注意: 服务器与存储对象需在同一个区下,如下示例
存储对象oss
云服务器 -->ECS 和 轻量级云服务器 均支持
1、 找到 存储对象控制台的内网访问地址
2、配置nginx 进行转发(配置Nginx)
转发到http://Bucket 名.oss-cn-shenzhen-
内网地址 ,-internal
指定服务 域名/oss 目录转发到存储对象服务 oss/ 目录下
完整配置
worker_processes 1;events {worker_connections 1024;}http {include mime.types;default_type application/octet-stream;sendfile on;keepalive_timeout 65;server {listen 80;server_name localhost;location / {root html;index index.html index.htm;}location /oss {proxy_pass http://Bucket 名.oss-cn-shenzhen-;}error_page 500 502 503 504 /50x.html;location = /50x.html {root html;}}}
3、通过Nginx 进行内网访问测试 (免流量费)
访问路径展示: http://xijia.plus/oss/qs44ufe2024qs44ufe2024.jpg
3、java - sdk 使用
1、添加 Maven 依赖
<!-- 阿里云OSS --><dependency><groupId>com.aliyun.oss</groupId><artifactId>aliyun-sdk-oss</artifactId><version>3.8.0</version></dependency>
2、添加自定义yml配置
添加配置
accessKeyId
accessKeySecret
endpoint
bucketName
## 阿里云oss配置aliyun:oss:# 阿里云下oss 的 accessKeyId和accessKeySecret(访问密钥,您可以在控制台上创建和查看)accessKeyId: accessKeySecret: # oss访问地址, 同阿里服务器可使用内网地址免费服务endpoint: oss-cn-# Bucket 名称bucketName: xijia-sz
3、OSSUtils 方法
/*** 示例说明* <p>* HelloOSS是OSS Java SDK的示例程序,您可以修改endpoint、accessKeyId、accessKeySecret、bucketName后直接运行。* 运行方法请参考README。* <p>* 本示例中的并不包括OSS Java SDK的所有功能,详细功能及使用方法,请参看“SDK手册 > Java-SDK”,* 链接地址是:/document_detail/oss/sdk/java-sdk/preface.html?spm=5176.docoss/sdk/java-sdk/。* <p>* 调用OSS Java SDK的方法时,抛出异常表示有错误发生;没有抛出异常表示成功执行。* 当错误发生时,OSS Java SDK的方法会抛出异常,异常中包括错误码、错误信息,详细请参看“SDK手册 > Java-SDK > 异常处理”,* 链接地址是:/document_detail/oss/sdk/java-sdk/exception.html?spm=5176.docoss/api-reference/error-response。* <p>* OSS控制台可以直观的看到您调用OSS Java SDK的结果,OSS控制台地址是:https://oss./index#/。* OSS控制台使用方法请参看文档中心的“控制台用户指南”, 指南的来链接地址是:/document_detail/oss/getting-started/get-started.html?spm=5176.docoss/user_guide。* <p>* OSS的文档中心地址是:/document_detail/oss/user_guide/overview.html。* OSS Java SDK的文档地址是:/document_detail/oss/sdk/java-sdk/install.html?spm=5176.docoss/sdk/java-sdk。*/package com.mon.aliyun.oss;import com.aliyun.oss.OSS;import com.aliyun.oss.OSSClientBuilder;import com.aliyun.oss.OSSException;import com.aliyun.oss.model.*;import com.mon.result.ResultEnum;import com.ws.ldy.config.error.ErrorException;import lombok.extern.slf4j.Slf4j;import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Service;import java.io.InputStream;import java.util.List;@Slf4j@Service//@Order(999)public class OSSUtils {/*** endpoint是访问OSS的域名。如果您已经在OSS的控制台上 创建了Bucket,请在控制台上查看域名。* 上传使用外网 endpoint* 下载使用内网 endpoint(只有在同地区下的阿里云服务器才可以访问)* <p>* // 上传* 外网流入流量免费 (上传免费)* 内网流入流量免费 (上传免费)* // 下载* 外网流出流量免费(按量计费, 闲是2.5毛 1GB,忙是 5毛1GB)* 内网流出流量免费(下载访问免费,同地域阿里云服务器可使用内网)*/// 阿里云下oss 接口访问地址@Value("${aliyun.oss.endpoint}")private String endpoint;// 阿里云下oss 的 accessKeyId和accessKeySecret(访问密钥,您可以在控制台上创建和查看)@Value("${aliyun.oss.accessKeyId}")private String accessKeyId;@Value("${aliyun.oss.accessKeySecret}")private String accessKeySecret;//阿里云oss下bucketName@Value("${aliyun.oss.bucketName}")private String bucketName;/*** TODO 上传文件到oss/file 目录下* <p>* 链接地址:/document_detail/oss/sdk/java-sdk/upload_object.html?spm=5176.docoss/user_guide/upload_object* </P>** @param yourObjectName 表示上传文件到OSS时需要指定包含文件后缀在内的完整路径,例如abc/efg/123.jpg。* @param inputStream 文件流* @return*/public boolean upload(String yourObjectName, InputStream inputStream) {// 创建ossClientOSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);// 创建PutObjectRequest对象。PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, yourObjectName, inputStream);// 设置 ContentType类型,防止图片等资源无法使用url直接访问ObjectMetadata metadata = new ObjectMetadata();metadata.setContentType(getContentType(yourObjectName.substring(yourObjectName.lastIndexOf("."))));putObjectRequest.setMetadata(metadata);// 开始上传ossClient.putObject(putObjectRequest);// 上传成功关闭OSSClient// ossClient.shutdown();log.info("上传-" + yourObjectName + " 成功");// 关闭OSSClient。ossClient.shutdown();return true;}/*** TODO 从OSS 下载文件* <p>* 下载文件。详细请参看“SDK手册 > Java-SDK > 下载文件”。* 链接地址是:/document_detail/oss/sdk/java-sdk/download_object.html?spm=5176.docoss/sdk/java-sdk/manage_object* </P>** @param yourObjectName 表示上文件在OSS时包含文件后缀在内的完整路径,例如abc/efg/123.jpg。* @return*/public InputStream download(String yourObjectName) {// 创建ossClientOSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);OSSObject ossObject = null;try {ossObject = ossClient.getObject(bucketName, yourObjectName);} catch (OSSException e) {e.printStackTrace();throw new ErrorException(ResultEnum.ADMIN_OSS_NO_PATH);}// 关闭OSSClient。ossClient.shutdown();//返回InputStreamreturn ossObject.getObjectContent();}/*** TODO 获取OSS 文件列表*/public List<OSSObjectSummary> getObjectListing() {// 创建ossClientOSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);ObjectListing objectListing = ossClient.listObjects(bucketName);List<OSSObjectSummary> objectSummary = objectListing.getObjectSummaries();// System.out.println("您有以下Object:");// for (OSSObjectSummary object : objectSummary) {// System.out.println("\t" + object.getKey());// }// 关闭OSSClient。ossClient.shutdown();return objectSummary;}/*** TODO 删除, 删除文件夹 --> 如: file/*/public boolean deleteObject(String firstKey) {// 创建ossClientOSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);ossClient.deleteObject(bucketName, firstKey);System.out.println("删除Object:" + firstKey + "成功。");// 关闭OSSClient。ossClient.shutdown();return true;}/*** TODO 判断获取文件保存内存** @param FilenameExtension* @return*/public static 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";}if (FilenameExtension.equalsIgnoreCase(".html")) {return "text/html";}if (FilenameExtension.equalsIgnoreCase(".txt")) {return "text/plain";}if (FilenameExtension.equalsIgnoreCase(".vsd")) {return "application/vnd.visio";}if (FilenameExtension.equalsIgnoreCase(".pptx") ||FilenameExtension.equalsIgnoreCase(".ppt")) {return "application/vnd.ms-powerpoint";}if (FilenameExtension.equalsIgnoreCase(".docx") ||FilenameExtension.equalsIgnoreCase(".doc")) {return "application/msword";}if (FilenameExtension.equalsIgnoreCase(".xml")) {return "text/xml";}if (FilenameExtension.equalsIgnoreCase(".mp4")) {return "video/mp4";}if (FilenameExtension.equalsIgnoreCase(".mp3")) {return "audio/mp3";}return "image/jpg";}}
4、controller 层方法
package com.ws.ldy.base.controller;import com.aliyun.oss.model.OSSObjectSummary;import com.mon.aliyun.oss.OSSUtils;import com.mon.result.Result;import com.mon.result.ResultEnum;import com.mon.utils.LocalDateTimeUtils;import com.ws.ldy.config.error.ErrorException;import io.swagger.annotations.Api;import io.swagger.annotations.ApiImplicitParam;import io.swagger.annotations.ApiImplicitParams;import io.swagger.annotations.ApiOperation;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.RestController;import org.springframework.web.multipart.MultipartFile;import java.io.*;import java.util.List;/*** TODO 阿里云OSS 文件上传下载** @author peter /10/20 21:32*/@RestController@Api(value = "FileOSSController", tags = "文件管理--阿里云OSS")@RequestMapping("/ossFile")public class FileOSSController extends BaseController {// 阿里云oss工具类@Autowiredprivate OSSUtils ossUtils;// 文件内网访问域名(下载访问,上传)private final String YM_PATH = "http://xijia.plus/"; //外网: xijia-sz.oss-cn-// 文件保存路径private final static String FILE_PATH = "oss/file/";// 文件保存路径地址private final static String UPLOAD_PATH_IMAGE = "image"; // oss/file/imageprivate final static String UPLOAD_PATH_MUSIC = "music"; // oss/file/musicprivate final static String UPLOAD_PATH_VIDEO = "video";private final static String UPLOAD_PATH_EXCEL = "excel";@RequestMapping(value = "/upload", method = RequestMethod.POST) //consumes = "multipart/*", headers = "content-type=multipart/form-data"@ApiOperation("OSS-文件上传,返回完整可访问当前服务内网访问OSS的完整URL")@ApiImplicitParams({@ApiImplicitParam(name = "filePath", value = "文件路径,必须指定开头目录(image/ -图片, music/ -音乐,video/ -视频,excel/ -表格)", required = true)})public Result<String> uploadImage(@RequestParam("file") MultipartFile file, @RequestParam("filePath") String filePath) {// 验证文件格式及路径,并获取文件上传路径, file.getOriginalFilename()=原文件名String fileName = getPath(filePath, file.getOriginalFilename());try {// 获得上传的文件流InputStream inputStream = file.getInputStream();// 上传到OSS的路径 = ObjectKeyString path = FILE_PATH + filePath + fileName;ossUtils.upload(path, inputStream);// 返回内网访问地址(域名+ oss存储路径)return Result.success(YM_PATH + path);} catch (Exception e) {return Result.error(ResultEnum.SYS_ERROR.getCode(), "文件上传失败");}}/*** TODO 文件下载** @param filePath 文件路径*/@ApiOperation("OSS-文件下载")@ApiImplicitParam(name = "filePath", value = "文件保存的完整可访问URL,或OSS相对路径", required = true)@RequestMapping(value = "/download", method = RequestMethod.GET)public void download(@RequestParam String filePath) {// 去除域名 ,获得oss存储路径filePath = filePath.replace(YM_PATH, "");// 获取文件名称String fileName = filePath.substring(filePath.lastIndexOf("/") + 1, filePath.length());// 从oss获取文件流InputStream inputStream = ossUtils.download(filePath);try {// 下载BufferedInputStream in = new BufferedInputStream(inputStream);// 设置response的Headerresponse.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes()));response.setContentType("application/octet-stream");response.setHeader("content-type", "application/octet-stream");// 放入outputStream流OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());byte[] buffer = new byte[1024];int len = 0;int i = 0;while ((len = in.read(buffer)) > 0) {i = i + len;outputStream.write(buffer, 0, len);}//最后的内容outputStream.write(buffer);//响应返回字节长度-无效:response.addHeader("Content-Length", "" + i);// System.out.println(i);outputStream.flush();outputStream.close();} catch (IOException ex) {ex.printStackTrace();throw new ErrorException(ResultEnum.SYS_ERROR.getCode(), "文件下载失败");}}/*** TODO oss-文件列表*/@ApiOperation("OSS-文件Object列表")@RequestMapping(value = "/fileList", method = RequestMethod.GET)public Result<List<OSSObjectSummary>> fileList() {List<OSSObjectSummary> objectListing = ossUtils.getObjectListing();return Result.success(objectListing);}/*** TODO oss-文件删除*/@ApiOperation("OSS-文件删除")@ApiImplicitParam(name = "filePath", value = "文件保存的完整可访问URL,或OSS相对路径", required = true)@RequestMapping(value = "/del", method = RequestMethod.DELETE)public Result del(@RequestParam String filePath) {// 去除域名 ,获得oss存储路径filePath = filePath.replace(YM_PATH, "");ossUtils.deleteObject(filePath);return Result.success();}/*** 上传路径文件格式判断** @param filePath 文件上传路径* @param fileName 文件名称* @return fileName*/private String getPath(String filePath, String fileName) {if (filePath.lastIndexOf("/") != filePath.length() - 1) {throw new ErrorException(100000, "路径必须已[/]结尾");}// 目录开头String[] path = filePath.split("/");// 后缀名String suffixName = fileName.substring(fileName.indexOf(".") + 1, fileName.length());if (UPLOAD_PATH_IMAGE.equals(path[0])) {// 图片if (!"jpg".equals(suffixName) && !"png".equals(suffixName)) {throw new ErrorException(100001, "图片仅支持上传-[jpg,png]");}//修改fileName的引用,提交17位时间+3位随机数(20前缀)fileName = LocalDateTimeUtils.getTimeStr20() + "-" + fileName;// filePath = filePath.replace(suffixName, "") + UUIDUtil.creatUUID() + "-";} else if (UPLOAD_PATH_MUSIC.equals(path[0])) {// 音乐if (!"mp3".equals(suffixName)) {throw new ErrorException(100002, "音乐仅支持上传-[mp3]");}} else if (UPLOAD_PATH_VIDEO.equals(path[0])) {// 视频if (!"mp4".equals(suffixName)) {throw new ErrorException(100003, "视频仅支持上传-[mp4]");}} else if (UPLOAD_PATH_EXCEL.equals(path[0])) {//excelif (!"xlsx".equals(suffixName) && !"xls".equals(suffixName)) {throw new ErrorException(100004, "EXCEL仅支持上传-[xlxs,xlx]");}} else {throw new ErrorException(100005, "路径错误");}return fileName;}}
5、swaager展示
注意: 使用接口删除文件夹,内文件必须为空,使用文件夹名上/, 如: file/
6、官方提供的示例Demo,HelloOSS.java
/*** 示例说明* * HelloOSS是OSS Java SDK的示例程序,您可以修改endpoint、accessKeyId、accessKeySecret、bucketName后直接运行。* 运行方法请参考README。* * 本示例中的并不包括OSS Java SDK的所有功能,详细功能及使用方法,请参看“SDK手册 > Java-SDK”,* 链接地址是:/document_detail/oss/sdk/java-sdk/preface.html?spm=5176.docoss/sdk/java-sdk/。* * 调用OSS Java SDK的方法时,抛出异常表示有错误发生;没有抛出异常表示成功执行。* 当错误发生时,OSS Java SDK的方法会抛出异常,异常中包括错误码、错误信息,详细请参看“SDK手册 > Java-SDK > 异常处理”,* 链接地址是:/document_detail/oss/sdk/java-sdk/exception.html?spm=5176.docoss/api-reference/error-response。* * OSS控制台可以直观的看到您调用OSS Java SDK的结果,OSS控制台地址是:https://oss./index#/。* OSS控制台使用方法请参看文档中心的“控制台用户指南”, 指南的来链接地址是:/document_detail/oss/getting-started/get-started.html?spm=5176.docoss/user_guide。* * OSS的文档中心地址是:/document_detail/oss/user_guide/overview.html。* OSS Java SDK的文档地址是:/document_detail/oss/sdk/java-sdk/install.html?spm=5176.docoss/sdk/java-sdk。* */package com.aliyun.oss.demo;import com.aliyun.oss.ClientException;import com.aliyun.oss.OSS;import com.aliyun.oss.OSSClientBuilder;import com.aliyun.oss.OSSException;import com.aliyun.oss.model.BucketInfo;import com.aliyun.oss.model.OSSObject;import com.aliyun.oss.model.OSSObjectSummary;import com.aliyun.oss.model.ObjectListing;import org.apache.log4j.Logger;import org.apache.log4j.PropertyConfigurator;import java.io.*;import java.util.List;public class HelloOSS {static Logger logger = Logger.getLogger(HelloOSS.class);// endpoint是访问OSS的域名。如果您已经在OSS的控制台上 创建了Bucket,请在控制台上查看域名。// 如果您还没有创建Bucket,endpoint选择请参看文档中心的“开发人员指南 > 基本概念 > 访问域名”,// 链接地址是:/document_detail/oss/user_guide/oss_concept/endpoint.html?spm=5176.docoss/user_guide/endpoint_region// endpoint的格式形如“http://oss-cn-/”,注意http://后不带bucket名称,// 比如“http://bucket-name.oss-cn-”,是错误的endpoint,请去掉其中的“bucket-name”。private static String endpoint = "http://oss-cn-";// accessKeyId和accessKeySecret是OSS的访问密钥,您可以在控制台上创建和查看,// 创建和查看访问密钥的链接地址是:https://ak-/#/。// 注意:accessKeyId和accessKeySecret前后都没有空格,从控制台复制时请检查并去除多余的空格。private static String accessKeyId = "<yourAccessKeyId>";private static String accessKeySecret = "<yourAccessKeySecret>";// Bucket用来管理所存储Object的存储空间,详细描述请参看“开发人员指南 > 基本概念 > OSS基本概念介绍”。// Bucket命名规范如下:只能包括小写字母,数字和短横线(-),必须以小写字母或者数字开头,长度必须在3-63字节之间。private static String bucketName = "<yourBucketName>";// Object是OSS存储数据的基本单元,称为OSS的对象,也被称为OSS的文件。详细描述请参看“开发人员指南 > 基本概念 > OSS基本概念介绍”。// Object命名规范如下:使用UTF-8编码,长度必须在1-1023字节之间,不能以“/”或者“\”字符开头。private static String firstKey = "my-first-key";public static void main(String[] args) {// 日志配置,OSS Java SDK使用log4j记录错误信息。示例程序会在工程目录下生成“oss-demo.log”日志文件,默认日志级别是INFO。// 日志的配置文件是“conf/log4j.properties”,如果您不需要日志,可以没有日志配置文件和下面的日志配置。PropertyConfigurator.configure("conf/log4j.properties");logger.info("Started");// 生成OSSClient,您可以指定一些参数,详见“SDK手册 > Java-SDK > 初始化”,// 链接地址是:/document_detail/oss/sdk/java-sdk/init.html?spm=5176.docoss/sdk/java-sdk/get-startOSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);try {// 判断Bucket是否存在。详细请参看“SDK手册 > Java-SDK > 管理Bucket”。// 链接地址是:/document_detail/oss/sdk/java-sdk/manage_bucket.html?spm=5176.docoss/sdk/java-sdk/initif (ossClient.doesBucketExist(bucketName)) {System.out.println("您已经创建Bucket:" + bucketName + "。");} else {System.out.println("您的Bucket不存在,创建Bucket:" + bucketName + "。");// 创建Bucket。详细请参看“SDK手册 > Java-SDK > 管理Bucket”。// 链接地址是:/document_detail/oss/sdk/java-sdk/manage_bucket.html?spm=5176.docoss/sdk/java-sdk/initossClient.createBucket(bucketName);}// 查看Bucket信息。详细请参看“SDK手册 > Java-SDK > 管理Bucket”。// 链接地址是:/document_detail/oss/sdk/java-sdk/manage_bucket.html?spm=5176.docoss/sdk/java-sdk/initBucketInfo info = ossClient.getBucketInfo(bucketName);System.out.println("Bucket " + bucketName + "的信息如下:");System.out.println("\t数据中心:" + info.getBucket().getLocation());System.out.println("\t创建时间:" + info.getBucket().getCreationDate());System.out.println("\t用户标志:" + info.getBucket().getOwner());// 把字符串存入OSS,Object的名称为firstKey。详细请参看“SDK手册 > Java-SDK > 上传文件”。// 链接地址是:/document_detail/oss/sdk/java-sdk/upload_object.html?spm=5176.docoss/user_guide/upload_objectInputStream is = new ByteArrayInputStream("Hello OSS".getBytes());ossClient.putObject(bucketName, firstKey, is);System.out.println("Object:" + firstKey + "存入OSS成功。");// 下载文件。详细请参看“SDK手册 > Java-SDK > 下载文件”。// 链接地址是:/document_detail/oss/sdk/java-sdk/download_object.html?spm=5176.docoss/sdk/java-sdk/manage_objectOSSObject ossObject = ossClient.getObject(bucketName, firstKey);InputStream inputStream = ossObject.getObjectContent();StringBuilder objectContent = new StringBuilder();BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));while (true) {String line = reader.readLine();if (line == null)break;objectContent.append(line);}inputStream.close();System.out.println("Object:" + firstKey + "的内容是:" + objectContent);// 文件存储入OSS,Object的名称为fileKey。详细请参看“SDK手册 > Java-SDK > 上传文件”。// 链接地址是:/document_detail/oss/sdk/java-sdk/upload_object.html?spm=5176.docoss/user_guide/upload_objectString fileKey = "README.md";ossClient.putObject(bucketName, fileKey, new File("README.md"));System.out.println("Object:" + fileKey + "存入OSS成功。");// 查看Bucket中的Object。详细请参看“SDK手册 > Java-SDK > 管理文件”。// 链接地址是:/document_detail/oss/sdk/java-sdk/manage_object.html?spm=5176.docoss/sdk/java-sdk/manage_bucketObjectListing objectListing = ossClient.listObjects(bucketName);List<OSSObjectSummary> objectSummary = objectListing.getObjectSummaries();System.out.println("您有以下Object:");for (OSSObjectSummary object : objectSummary) {System.out.println("\t" + object.getKey());}// 删除Object。详细请参看“SDK手册 > Java-SDK > 管理文件”。// 链接地址是:/document_detail/oss/sdk/java-sdk/manage_object.html?spm=5176.docoss/sdk/java-sdk/manage_bucketossClient.deleteObject(bucketName, firstKey);System.out.println("删除Object:" + firstKey + "成功。");ossClient.deleteObject(bucketName, fileKey);System.out.println("删除Object:" + fileKey + "成功。");} catch (OSSException oe) {oe.printStackTrace();} catch (ClientException ce) {ce.printStackTrace();} catch (Exception e) {e.printStackTrace();} finally {ossClient.shutdown();}logger.info("Completed");}}
本文到此结束,如果觉得有用,动动小手点赞或关注一下呗,将不定时持续更新更多的内容…,感谢大家的观看!
阿里云oss 使用 基于Nginx 配置云服务器+oss的内网访问 及使用Java SDK 完成上传 下载 删除 查询文件列表操作