七牛云工具类
依赖pom.xml文件:
<dependency> <groupId>com.qiniu</groupId> <artifactId>qiniu-java-sdk</artifactId> <version>7.7.0</version> </dependency>
代码QiniuUtil:
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 org.springframework.web.multipart.MultipartFile;
public class QiniuUtil {
//更改三个配置
private static String accessKey = "GwjVLqcRbHYMHzoybyyjMTHjRITCJ77ogKjI4y2T";
private static String secretKey = "Qi7LYlbqOy36y-mbEFLIiwjONzpZM4onVtpaKq3W";
private static String bucket = "770866";
public static void uploadFile(MultipartFile uploadFile, String filename) {
Configuration cfg = new Configuration(Region.region0());
UploadManager uploadManager = new UploadManager(cfg);
String key = filename; //不使用hash值,用Uuid
try {
byte[] uploadBytes = uploadFile.getBytes();
Auth auth = Auth.create(accessKey, secretKey);
String upToken = auth.uploadToken(bucket);
try {
Response response = uploadManager.put(uploadBytes, key, upToken);
DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
// System.out.println(putRet.key);
System.out.println(putRet.hash);
} catch (QiniuException ex) {
Response r = ex.response;
System.err.println(r.toString());
try {
System.err.println(r.bodyString());
} catch (QiniuException ex2) {
}
}
} catch (Exception ex) {
}
}
public static void removefile(String fileName) {
Configuration cfg = new Configuration(Region.region0());
String key = fileName;
Auth auth = Auth.create(accessKey, secretKey);
BucketManager bucketManager = new BucketManager(auth, cfg);
try {
bucketManager.delete(bucket, key);
} catch (QiniuException ex) {
System.err.println(ex.code());
System.err.println(ex.response.toString());
}
}
}