转载请注明来源: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。

具体SDK介绍參看官网链接:

spm=5176.383663.13.1.J6I4Ga">https://help.aliyun.com/document_detail/oss/sdk/java-sdk/preface.html?

spm=5176.383663.13.1.J6I4Ga

<!-- 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文件上传服务的更多相关文章

  1. 记一次阿里云oss文件上传服务假死

    引言 记得以前刚开始学习web项目的时候,经常涉及到需要上传图片啥的,那时候都是把图片上传到当前项目文件夹下面,每次项目一重启图片就丢了.虽然可以通过修改/tomcat/conf/server.xml ...

  2. PHP实现阿里云OSS文件上传(支持批量)

    上传文件至阿里云OSS,整体逻辑是,文件先临时上传到本地,然后在上传到OSS,最后删除本地的临时文件(也可以不删,具体看自己的业务需求),具体实现流程如下:   1.下载阿里云OSS对象上传SDK(P ...

  3. SpringBoot整合阿里云OSS文件上传、下载、查看、删除

    1. 开发前准备 1.1 前置知识 java基础以及SpringBoot简单基础知识即可. 1.2 环境参数 开发工具:IDEA 基础环境:Maven+JDK8 所用技术:SpringBoot.lom ...

  4. php阿里云oss文件上传

    php的文件上传 文件上传 php的文件上传放在了$_FILES数组里,单文件和多文件上传的区别在于$_FILES['userfile']['name']是否为数组, 不熟悉的可以读一下官方文档 单文 ...

  5. 阿里云OSS文件上传封装

    1.先用composer安装阿里云OSS的PHPSDK 2.配置文件里定义阿里云OSS的秘钥 3.在index控制器里的代码封装 <?php namespace app\index\contro ...

  6. 记录-阿里云Oss文件上传

    public class OssUtil { /** * 上传图片 * @param file * @param request * @return */ public static Map<S ...

  7. Thinkphp整合阿里云OSS图片上传实例

    Thinkphp3.2整合阿里云OSS图片上传实例,图片上传至OSS可减少服务器压力,节省宽带,安全又稳定,阿里云OSS对于做负载均衡非常方便,不用传到各个服务器了 首先引入阿里云OSS类库 < ...

  8. SpringBoot完美配置阿里云的文件上传

    新建一个config类 AliyunOSS.java @Configuration @Data public class AliyunOSS { private OSSClient ossClient ...

  9. 阿里云OSS图片上传类

    1.阿里云基本函数 /** * 把本地变量的内容到文件 * 简单上传,上传指定变量的内存值作为object的内容 */ public function putObject($imgPath,$obje ...

随机推荐

  1. LintCode: Single Number II

    一篇解析比较详细的文章:http://www.acmerblog.com/leetcode-single-number-ii-5394.html C++ 解法(1) 求出每个比特位的数目,然后%3,如 ...

  2. 微软BI 之SSRS 系列 - 使用分组 Group 属性实现基于父子递归关系的汇总报表

    基于父子关系的递归结构在公司组织结构里比较常见,基本上都是在一张表里实现的自引用关系.在报表中如果要实现这种效果,并且在这个基础上做一些数据的汇总,可以使用到下面提到的方法. 要实现的效果大致如下 - ...

  3. DFS研究

    1.DFS和杀毒软件的影响:http://www.symantec.com/connect/forums/sep-and-dfs-replication 2.DFS深度:http://technet. ...

  4. python xlwt写excel格式控制 颜色、模式、编码、背景色

    关于写excel的格式控制,比如颜色等等 import xlwt from datetime import datetime font0 = xlwt.Font() font0.name = 'Tim ...

  5. Nginx 与Tomcat 实现动静态分离、负载均衡

    Nginx 与Tomcat 实现动静态分离.负载均衡 一.Nginx简介: Nginx一个高性能的HTTP和反向代理服务器, 具有很高的稳定性和支持热部署.模块扩展也很容易.当遇到访问的峰值,或者有人 ...

  6. MySQL登陆小问题

    root用户创建用户 CREATE USER gechong IDENTIFIED BY 'gechong'; 登录数据库时提示错误: C:\Users\gechong>mysql -u gec ...

  7. CentOS静默安装Oracle 11gR2(x64)

    环境 OS: CentOS 7.4; hosts: L134; IP: 192.168.1.134 DB: linux.x64_11gR2_database 安装依赖包 yum install -y ...

  8. Linux Shell 下载网站指定文件

    Shell脚本,用来从网站下载指定文件名的文件.先判断本地这个文件是否存在,如果存在则忽略,不存在则从远程服务器上下载,下载成功后本地的批次号累加1,然后使用新的批次号继续下载新文件. #!/bin/ ...

  9. 《Android源代码设计模式解析与实战》读书笔记(十)

    第十章.解释器模式 解释器模式是一种用的比較少的行为型模式.其提供了一种解释语言的语法或表达式的方式. 可是它的使用场景确实非常广泛,仅仅是由于我们自己非常少回去构造一个语言的文法,所以使用较少. 1 ...

  10. json在线解析

    http://json.cn/ 一个非常不错的,json格式学习和处理的网站