java上传文件和图片到七牛云空间

时间:2022-08-23 16:29:01
package com.zkja.sp.common;

import java.io.File;
import java.io.UnsupportedEncodingException;
import org.apache.log4j.Logger;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.zkja.v1.push.service.V1Sender;

public class QiNiu {

private static Logger logger = Logger.getLogger(V1Sender.class);

       // AK/SK 存储空间名称

public static final String ACCESS_KEY = "********fdcXzTRncjiOc_8Nl2Qfy**ugsdSLatK";

public static final String SECRET_KEY = "*********9XctxiFsvnzR_7QX5**EI4--maNgfsdgrC";

       //存储空间名

public static final String bucket = "picture"; //七牛云空间存储空间名称(存图片)
public static final String bucket1 = "documentfile";//七牛云空间存储空间名称(存文档)


public static String token(String bucketName) {
Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
String upToken = auth.uploadToken(bucketName);
return upToken;
}

/**
* 默认存储空间
* @return
*/
public static String token() {
Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
String upToken = auth.uploadToken(bucket);
return upToken;
}

/**
* 上传一个文件(传文件路径)
* @param filePath
* @param fileName
* @return
*/
public static String uploadFile(String filePath, String fileName, String bucketName, int zoneName) {
try {
Zone zone= Zone.zoneNa0();
if(zoneName==0){    //华南
zone=Zone.zone0();
}
if(zoneName==1){    //华北
zone=Zone.zone0();
}
if(zoneName==2){    //华东
zone=Zone.zone0();
}

Configuration cfg = new Configuration(zone);
UploadManager uploadManager = new UploadManager(cfg);
Response response = uploadManager.put(filePath, fileName, token(bucketName));
// 解析上传成功的结果
DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
System.out.println(putRet.key);
System.out.println(putRet.hash);
return putRet.key;
} catch (QiniuException ex) {
Response r = ex.response;
logger.info(fileName+"----文件上传失败----"+r.toString());
try {
System.err.println(r.bodyString());
logger.info(fileName+"----文件上传失败----"+r.toString());
} catch (QiniuException ex2) {
// ignore
}
return null;
}

}


/**
 * 上传一个文件(传文件)
 * @param filePath
 * @param fileName
 * @return
 */
public static String uploadFile(File file, String fileName, String bucketName, int zoneName) {
try {
Zone zone= Zone.zoneNa0();
if(zoneName==0){    //华南
zone=Zone.zone0();
}
if(zoneName==1){    //华北
zone=Zone.zone0();
}
if(zoneName==2){    //华东
zone=Zone.zone0();
}

Configuration cfg = new Configuration(zone);
UploadManager uploadManager = new UploadManager(cfg);
Response response = uploadManager.put(file, fileName, token(bucketName));
// 解析上传成功的结果
DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
System.out.println(putRet.key);
System.out.println(putRet.hash);
return putRet.key;
} catch (QiniuException ex) {
Response r = ex.response;
logger.info(fileName+"----文件上传失败----"+r.toString());
try {
System.err.println(r.bodyString());
logger.info(fileName+"----文件上传失败----"+r.toString());
} catch (QiniuException ex2) {
// ignore
}
return null;
}
}


/**
* 上传一个字符串
* @param uploadString
* @param key
* @return
*/
public static String uploadByte(String uploadString,String key,int zoneName){
try {
    byte[] uploadBytes = uploadString.getBytes("utf-8");
    try {
    Zone zone= Zone.zoneNa0();
if(zoneName==0){    //华南
zone=Zone.zone0();
}
if(zoneName==1){    //华北
zone=Zone.zone0();
}
if(zoneName==2){    //华东
zone=Zone.zone0();
}
    Configuration cfg = new Configuration(zone);
UploadManager uploadManager = new UploadManager(cfg);
        Response response = uploadManager.put(uploadBytes, key, token());
        //解析上传成功的结果
        DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
        System.out.println(putRet.key);
        System.out.println(putRet.hash);
        
        return putRet.key;
    } catch (QiniuException ex) {
        Response r = ex.response;
        System.err.println(r.toString());
        logger.info(uploadString+"----上传失败----"+r.toString());
        try {
            System.err.println(r.bodyString());
            logger.info(uploadString+"----上传失败----"+r.toString());
        } catch (QiniuException ex2) {
            //ignore
        }
        return null;
    }
} catch (UnsupportedEncodingException ex) {
    //ignore
return null;
}
}

/**
* 根据Key值删除云端文件
* @param key
*/
public static Boolean deleteFile(String key){
Configuration cfg = new Configuration(Zone.zone2());
Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
BucketManager bucketManager = new BucketManager(auth, cfg);
try {
Response result =  bucketManager.delete(bucket, key);
System.err.println(new Gson().toJson(result));
if(result.statusCode==200){
return true;
}
} catch (QiniuException ex) {
    //如果遇到异常,说明删除失败
logger.info(key+"----删除失败----"+ex.code());
logger.info(key+"----删除失败----"+ex.response.toString());
    System.err.println(ex.code());
    System.err.println(ex.response.toString());
}
return false;
}

}


package com.zkja.sp.test;
import org.junit.Test;

import com.zkja.sp.common.QiNiu;

/**

测试类

public class Test3 {


       @Test 
public void uploadImage() throws Exception{
String filePath="C:\\Users\\sinotechs\\Desktop\\test0.jpg";
String fileName = "test0.jpg";
String result = QiNiu.uploadFile(filePath, fileName, QiNiu.bucket, 2);
System.err.println(result);
}

@Test 
public void uploadImageOther() throws Exception{
String filePath="C:\\Users\\sinotechs\\Desktop\\test0.jpg";
String fileName = "test0.jpg";
String result = QiNiu.uploadFile(filePath, fileName, QiNiu.bucket1, 0);
System.err.println(result);
}

@Test 
public void deleteImage() throws Exception{
String filePath="C:\\Users\\sinotechs\\Desktop\\test0.jpg";
String fileName = "test0.jpg";

String hashkey = "FkeNitWRsrfd3am6nOFf6-MMZuDk";
boolean result = QiNiu.deleteFile(fileName);
if(result){
System.err.println("删除成功");
}else {
System.err.println("删除失败");
}
}

}

java上传文件和图片到七牛云空间

java上传文件和图片到七牛云空间

七牛云jar包:https://download.csdn.net/download/fzqzxx/10298334