首先我们需要创建一个oss.properties文件存储七牛云的必须属性,可在七牛云官网查看
#qiniu.bucket= xxx #qiniu.access_key= xxx #qiniu.secret_key= xxx #qiniu.base_url= xxx
七牛工具类QiniuOssUtils
import com.google.gson.Gson; import com.qiniu.common.QiniuException; import com.qiniu.http.Response; import com.qiniu.storage.BucketManager; import com.qiniu.storage.Configuration; import com.qiniu.storage.Region; import com.qiniu.storage.UploadManager; import com.qiniu.storage.model.DefaultPutRet; import com.qiniu.util.Auth;import java.io.*; import java.util.Properties;/*** 七牛OSS管理工具*/ public class QiniuOssUtils {/*** 存储空间名*/private static String BUCKET;/*** accessKey和secretKey*/private static String ACCESS_KEY;private static String SECRET_KEY;/*** 外网访问地址(内置域名有效期只有30天)*/private static String BASE_URL;/*** 上传管理器*/private UploadManager upload;/*** 桶管理器(存储空间管理器)*/private BucketManager bucket;static {InputStream in = null;try {in = QiniuOssUtils.class.getResourceAsStream("/oss.properties");Properties p = new Properties();p.load(in);BUCKET = p.getProperty("qiniu.bucket");ACCESS_KEY = p.getProperty("qiniu.access_key");SECRET_KEY = p.getProperty("qiniu.secret_key");BASE_URL = p.getProperty("qiniu.base_url");} catch (IOException e) {e.printStackTrace();} finally {if (in != null) {try {in.close();} catch (IOException e) {e.printStackTrace();}}}}public QiniuOssUtils() {this(Region.autoRegion());}public QiniuOssUtils(Region region) {//创建配置对象Configuration cfg = new Configuration(region);//创建上传管理器upload = new UploadManager(cfg);//创建存储空间管理器bucket = new BucketManager(getAuth(), cfg);}/*** 返回认证器(包含的访问密钥)** @return*/private Auth getAuth() {return Auth.create(ACCESS_KEY, SECRET_KEY);}/*** 获取令牌对象(服务器返回的授权信息)** @return*/private String getToken() {return getAuth().uploadToken(BUCKET);}/*** 文件上传** @param file* @return*/public String upload(File file, String key) {try {return upload(new FileInputStream(file), key);} catch (FileNotFoundException | QiniuException e) {e.printStackTrace();}return null;}/*** 上传文件** @param is* @param key* @return* @throws QiniuException*/public String upload(InputStream is, String key) throws QiniuException {//上传流Response response = upload.put(is, key, getToken(), null, null);//解析返回结果DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);//将文件的访问地址返回return BASE_URL + putRet.key;}/*** 删除文件** @param key*/public void delete(String key) {try {bucket.delete(BUCKET, key);} catch (QiniuException e) {e.printStackTrace();}} }