构建基于阿里云OSS文件上传服务
转载请注明来源:http://blog.csdn.net/loongshawn/article/details/50710132
1. 阿里云OSS服务介绍
对象存储(Object Storage Service,简称OSS),是阿里云提供的海量、安全和高可靠的云存储服务。在OSS中每一个文件都有一个key。通过这个key来指向不同的文件对象。
同一时候大家要明确。在OSS中是没有目录的概念。假设你在web管理平台上看到了目录的形式,那是阿里云为了大家的操作习惯虚构出来了。
如你提交的key为“/attachment/2016/123.txt”,那么在web管理平台上你能够看到上述以“/”分开的目录形式,事实上在OSS他的key就是“/attachment/2016/123.txt”
2. 阿里云OSS Java SDK
阿里云官方有针对不同语言设计的SDK包,本文使用java SDK。
<!-- OSS Java SDK -->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>2.1.0</version>
</dependency>
3. 怎样使用OSS
阿里云OSS服务,通过自身提供的Client来实现上传和下载。
所以在使用OSS服务上传文件时,须要构建三个类:Client类、Config类、上传类。
4. 构建OSS Client类
採用单例模式构建OSSClient。
package com.autonavi.oss.client;
import com.aliyun.oss.OSSClient;
import com.autonavi.constants.Constant;
import com.autonavi.oss.conf.DefaultClientConfiguration;
public class DefaultOSSClient {
/*
* Constructs a client instance with your account for accessing OSS
*/
private static OSSClient client = new OSSClient(Constant.endpoint, Constant.accessKeyId, Constant.accessKeySecret,DefaultClientConfiguration.getDefalutClientConfig());
private DefaultOSSClient() {
}
public static OSSClient getDefaultOSSClient(){
if(client == null){
client = new OSSClient(Constant.endpoint, Constant.accessKeyId, Constant.accessKeySecret,DefaultClientConfiguration.getDefalutClientConfig());
}
return client;
}
public static void shutdownOSSClient(){
client.shutdown();
client = null;
}
}
5. 构建OSS Config类
配置OSSClient所须要的属性。
package com.autonavi.oss.conf;
import com.aliyun.oss.ClientConfiguration;
public class DefaultClientConfiguration {
private static final ClientConfiguration conf = new ClientConfiguration();
private DefaultClientConfiguration() {
// Set the maximum number of allowed open HTTP connections
conf.setMaxConnections(100);
// Set the amount of time to wait (in milliseconds) when initially establishing
// a connection before giving up and timing out
conf.setConnectionTimeout(5000);
// Set the maximum number of retry attempts for failed retryable requests
conf.setMaxErrorRetry(3);
// Set the amount of time to wait (in milliseconds) for data to betransfered over
// an established connection before the connection times out and is closed
conf.setSocketTimeout(2000);
}
public static ClientConfiguration getDefalutClientConfig(){
return conf;
}
}
6. 构建OSS 文件上传类
OSS文件上传,支持两种方式:1、File;2、InputStream,所以设计了两种模式相应的方法,大同小异。上传类中须要注意一点就是并发的问题。由于当前存储文件是依照时间戳来存储,所以对方法中的这种方法getCurrentTimeStamp()加了synchronized同步处理。
package com.autonavi.oss.put;
import java.io.File;
import java.io.InputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.PutObjectRequest;
import com.autonavi.constants.Constant;
import com.autonavi.oss.client.DefaultOSSClient;
import com.autonavi.utils.Date2Str;
/**
* @author loongshawn
* @date 2016-01-28
* @category OSS文件上传。支持两种方式:1、File。2、InputStream
* @paras ArrayList<File> files
*/
public class OSSUpload {
private static final Logger logger = LoggerFactory.getLogger(OSSUpload.class);
public static String put1(File file){
String return_key = null;
try {
OSSClient client = DefaultOSSClient.getDefaultOSSClient();
if(file != null){
String fileName = file.getName();
/**
* getCurrentTimeStamp()方法为同步方法,确保时间戳的唯一性。
*/
String timeStamp = Date2Str.getCurrentTimeStamp();
String timeDate = Date2Str.getCurrentDate5();
String key = Constant.bashFilePath + timeDate + timeStamp +"/"+fileName;
client.putObject(new PutObjectRequest(Constant.bucketName, key, file));
}
DefaultOSSClient.shutdownOSSClient();
} catch (ClientException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
logger.info("OSSUpload.put1 error:" + e.toString());
return null;
}
return return_key;
}
public static String put2(InputStream in, String filename){
String return_key = null;
try {
OSSClient client = DefaultOSSClient.getDefaultOSSClient();
if(in != null){
String fileName = filename;
/**
try {
fileName = new String(filename.getBytes("ISO-8859-1"),"UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
**/
/**
* getCurrentTimeStamp()方法为同步方法,确保时间戳的唯一性。
*/
String timeStamp = Date2Str.getCurrentTimeStamp();
String timeDate = Date2Str.getCurrentDate5();
String key = Constant.bashFilePath + timeDate + timeStamp +"/"+fileName;
client.putObject(new PutObjectRequest(Constant.bucketName, key, in));
return_key = key;
}
DefaultOSSClient.shutdownOSSClient();
} catch (ClientException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
logger.info("OSSUpload.put2 error:" + e.toString());
return null;
}
return return_key;
}
}
同步获取时间戳的方法。以防止并发时出现文件遗漏。
// 同步获取时间戳的方法。即一个时刻仅仅有一个方法被调用。即产生唯一时间戳
public static synchronized String getCurrentTimeStamp(){
String time = getDate(0,3);
return time;
}
7. 文件上传測试
7.1. 方式一:代码測试
public class FileUpload {
public static void main(String[] args){
try {
uploadOSS();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void uploadOSS() throws ClientProtocolException, IOException{
HttpPost httpPost = new HttpPost("http://127.0.0.1:7001/test/autonavi/shanghai/api/attachment/oss/");
httpPost.addHeader("key","123);
httpPost.addHeader("user","123");
httpPost.addHeader("method","123");
httpPost.addHeader("filename",new String("黄山[哈哈].jpg".getBytes("UTF-8"),"ISO-8859-1"));
httpPost.addHeader("type","01");
FileEntity reqEntity = new FileEntity(new File("/Users/123/Pictures/Huangshan.jpg"));
httpPost.setEntity(reqEntity);
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(httpPost);
System.out.println(response);
}
上传成功截图:
7.2. 方式二:工具提交測试
利用RestFul Client工具測试
上传成功截图:
8. 后记
当然编写的服务还有非常多不足之处,希望看过的朋友指正。
构建基于阿里云OSS文件上传服务的更多相关文章
- 记一次阿里云oss文件上传服务假死
引言 记得以前刚开始学习web项目的时候,经常涉及到需要上传图片啥的,那时候都是把图片上传到当前项目文件夹下面,每次项目一重启图片就丢了.虽然可以通过修改/tomcat/conf/server.xml ...
- PHP实现阿里云OSS文件上传(支持批量)
上传文件至阿里云OSS,整体逻辑是,文件先临时上传到本地,然后在上传到OSS,最后删除本地的临时文件(也可以不删,具体看自己的业务需求),具体实现流程如下: 1.下载阿里云OSS对象上传SDK(P ...
- SpringBoot整合阿里云OSS文件上传、下载、查看、删除
1. 开发前准备 1.1 前置知识 java基础以及SpringBoot简单基础知识即可. 1.2 环境参数 开发工具:IDEA 基础环境:Maven+JDK8 所用技术:SpringBoot.lom ...
- php阿里云oss文件上传
php的文件上传 文件上传 php的文件上传放在了$_FILES数组里,单文件和多文件上传的区别在于$_FILES['userfile']['name']是否为数组, 不熟悉的可以读一下官方文档 单文 ...
- 阿里云OSS文件上传封装
1.先用composer安装阿里云OSS的PHPSDK 2.配置文件里定义阿里云OSS的秘钥 3.在index控制器里的代码封装 <?php namespace app\index\contro ...
- 记录-阿里云Oss文件上传
public class OssUtil { /** * 上传图片 * @param file * @param request * @return */ public static Map<S ...
- Thinkphp整合阿里云OSS图片上传实例
Thinkphp3.2整合阿里云OSS图片上传实例,图片上传至OSS可减少服务器压力,节省宽带,安全又稳定,阿里云OSS对于做负载均衡非常方便,不用传到各个服务器了 首先引入阿里云OSS类库 < ...
- SpringBoot完美配置阿里云的文件上传
新建一个config类 AliyunOSS.java @Configuration @Data public class AliyunOSS { private OSSClient ossClient ...
- 阿里云OSS图片上传类
1.阿里云基本函数 /** * 把本地变量的内容到文件 * 简单上传,上传指定变量的内存值作为object的内容 */ public function putObject($imgPath,$obje ...
随机推荐
- UML关系(泛化,实现,依赖,关联(聚合,组合))
http://www.cnblogs.com/olvo/archive/2012/05/03/2481014.html UML类图关系(泛化 .继承.实现.依赖.关联.聚合.组合) 继承.实现.依赖. ...
- mycat分库分表 mod-long
转载自:http://blog.csdn.net/sunlihuo/article/details/54574903 下面是配置文件 schema.xml: <?xml version=&quo ...
- Objective-C编程 - 1. 浅谈内存分配
Objective-C语言的对象类型都必须用指针,对象所占的内存是在堆(heap)上分配的. NSString也必须在堆上分配,因此必须用指针. NSString *someString = @&qu ...
- iOS应用程序状态图
理解应用的状态对于我们开发iOS大有裨益. 当前应用所处什么状态,什么促使它在各个状态间进行过渡,你的代码又是如何 唤醒这些过渡,等等等等. 先请看下图: 1. 当应用出于非运行状态时,它处于图中的& ...
- ZH奶酪:PHP抓取网页方法总结
From:http://www.jb51.net/article/24343.htm 在做一些天气预报或者RSS订阅的程序时,往往需要抓取非本地文件,一般情况下都是利用php模拟浏览器的访问,通过ht ...
- 超具体Windows版本号编译执行React Native官方实例UIExplorer项目(多图慎入)
),React Native技术交流4群(458982758).请不要反复加群! 欢迎各位大牛,React Native技术爱好者加入交流!同一时候博客右側欢迎微信扫描关注订阅号,移动技术干货,精彩文 ...
- 不同版本的tomcat下载路径
1.由于安全问题,有些tomcat存在漏洞.为了升级要么修复漏洞,要么就直接升级tomcat. 一般升级tomcat比较省事.但是找到相应版本的tomcat比较难,所以还是要自己寻找对应的tomcat ...
- 关于gitblit在Windows中无法Start的问题
前期配置/data/defaults.properties文件,请自行百度 首先:找到该目录下的该文件 右键打开,找到SET ARCH=xx,将xx替换成x86 将该处的默认修改成配置环境变量的jvm ...
- Jenkins的安装(最为简单的安装方法)
1.Jenkins的安装(最为简单的安装方法) (1)下载Jenkins(一个war文件) (2)cmd运行:java -jar jenkins.war [Jenkins需要IDK1.5以上的版本] ...
- kibana对logstash监控获取不到数据
需求: kibana监控elasticsearch+kibana+logstash的性能寻找,性能瓶颈! 发现启动logstash加载logstash.yml,不读取配置好的xpack.monitor ...