依赖
<!-- 七牛 --> <dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp</artifactId> <version>3.3.1</version> <scope>compile</scope> </dependency> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.6.2</version> </dependency> <dependency> <groupId>com.qiniu</groupId> <artifactId>happy-dns-java</artifactId> <version>0.1.4</version> </dependency> <dependency> <groupId>com.qiniu</groupId> <artifactId>qiniu-java-sdk</artifactId> <version>7.2.1</version> </dependency>
import com.broadcast.app.constant.ConfigConstant; import com.qiniu.common.QiniuException; import com.qiniu.common.Zone; import com.qiniu.http.Response; import com.qiniu.storage.UploadManager; import com.qiniu.util.Auth; import com.qiniu.storage.Configuration; /** * Author:Quintin Tang Date:2017/3/2-9:28. */ public class QiNiuTest { public static void main(String[] args) { QiNiuTest qiNiuTest = new QiNiuTest(); qiNiuTest.upload("D:\\001.png"); } public void upload(String filePath) { //构造一个带指定Zone对象的配置类 //机房 Zone对象 华东 Zone.zone0()华北Zone.zone1()华南Zone.zone2()北美Zone.zoneNa0() Configuration cfg = new Configuration(Zone.zone2()); //创建上传对象 UploadManager uploadManager = new UploadManager(cfg); try { //调用put方法上传 Response res = uploadManager.put(filePath, null, getToekn()); //打印返回的信息 System.out.println(res.bodyString()); } catch (QiniuException e) { Response r = e.response; // 请求失败时打印的异常的信息 System.out.println(r.toString()); try { //响应的文本信息 System.out.println(r.bodyString()); } catch (QiniuException e1) { //ignore } } } public String getToekn() { //七牛的accesskey String accessKey = ConfigConstant.QINIU_ACCESSKEY; //七牛的secrectkey String secretKey = ConfigConstant.QINIU_SECRETKEY; //空间名称 String bucket = ConfigConstant.QINIU_BUCKET; //密钥配置 Auth auth = Auth.create(accessKey, secretKey); //获取token String upToken = auth.uploadToken(bucket); //覆盖上传 //String key = "file key"; //String upToken = auth.uploadToken(bucket, key); //覆盖上传除了需要简单上传所需要的信息之外,还需要想进行覆盖的文件名称,这个文件名称同时可是客户端上传代码中指定的文件名,两者必须一致。 System.out.println(upToken); return upToken; } }