java上传文件到七牛云

先引入七牛云SDK




  com.qiniu

  qiniu-java-sdk

  [7.2.0, 7.2.99]




import com.google.gson.Gson;

import com.qiniu.common.QiniuException;

import com.qiniu.http.Response;

import java.io.IOException;

import com.qiniu.storage.UploadManager;

import com.qiniu.storage.Configuration;

import com.qiniu.storage.model.DefaultPutRet;

import com.qiniu.util.Auth;

public class QiNiuFileUpUtil {

  //设置好账号的ACCESS_KEY和SECRET_KEY

  StringACCESS_KEY ="******";

  StringSECRET_KEY ="******";

  //要上传的空间名--

  Stringbucketname ="******";

  StringFilePath ="D:\\test.html";

  //密钥配置

  Authauth = Auth.create(ACCESS_KEY, SECRET_KEY);

  //创建上传对象

  UploadManageruploadManager =new UploadManager(new Configuration());

  //简单上传,使用默认策略,只需要设置上传的空间名就可以了

  public StringgetUpToken(){

return auth.uploadToken(bucketname);

  }

public Stringupload()throws IOException{

try {

//调用put方法上传

      String key = StringUtil.getUuid() +".html";//随机生成文件名

      Response res =uploadManager.put(FilePath, key, getUpToken());

    //这里返回的是 {"hash":"FrQF5eX_kNsNKwgGNeJ4TbBA0Xzr","key":"aa1.jpg"}

    //以下我们要获取其中key值

      DefaultPutRet putRet =new Gson().fromJson(res.bodyString(), DefaultPutRet.class);

      //打印返回的信息

        System.out.println(putRet.key);

        System.out.println(putRet.hash);

        System.out.println(res.statusCode);//200为上传成功

        return "http://七牛云域名"+putRet.key;

      }catch (QiniuException e) {

Response r = e.response;

          // 请求失败时打印的异常的信息

          System.out.println(r.toString());

          try {

//响应的文本信息

            System.out.println(r.bodyString());

          }catch (QiniuException e1) {

//ignore

          }

}

return "";

  }

}

你可能感兴趣的:(java上传文件到七牛云)