首先要添加七牛云的依赖:
代码如下:
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
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 lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.ResponseBody;
import org.apache.commons.io.IOUtils;
import java.io.*;
import java.net.URLEncoder;
/**
* @ProjectName: app-download
* @Package: com.dongfeng.aliap
* @ClassName: QiNiuOSSUtils
* @Author: zhy
* @Description: 七牛云存储
* @Date: 2020/11/20 12:42
* @Version: 1.0
*/
@Slf4j
public class QiNiuOSSUtils {
private static final String ACCESS_KEY = "你的AK";
private static final String SECRET_KEY = "你的SK";
private static final String DOMAIN_BUCKET = "你的域名";
private static final String BUCKET = "你的bucket";
/**
* 上传本地文件
* 将异常抛出到上层,由上层进行处理
*
* @param path
* @param localFilePath
* @param key 七牛云端的key对应文件名称,此处的key需要加上路径
* @return
*/
public static String uploadLocalFile(String localFilePath, String path, String key) throws QiniuException, UnsupportedEncodingException {
return uploadFile(new File(localFilePath), path, key);
}
/**
* 利用七牛云上传文件
*
* @param path 文件需要保存的路径
* @param file
* @param filename 文件需要保存的名称
* @return
* @throws QiniuException
*/
public static String uploadFile(File file, String path, String filename) throws QiniuException, UnsupportedEncodingException {
//构造一个带指定 Region 对象的配置类
Configuration cfg = new Configuration(Region.region1());
//...其他参数参考类注释
UploadManager uploadManager = new UploadManager(cfg);
Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
String upToken = auth.uploadToken(BUCKET);
//默认不指定key的情况下,以文件内容的hash值作为文件名
Response response = uploadManager.put(file, String.format("%s/%s", path, filename), upToken);
//解析上传成功的结果
log.debug("uploadFile response:{}", response.bodyString());
DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
log.debug("uploadFile response key: {}", putRet.key);
log.debug("uploadFile response hash: {}", putRet.hash);
return getDownloadUrl(path, filename);
}
/**
* 七牛字节流上传
*
* @param path 在七牛云上保存的路径
* @param inputStream
* @param filename 文件保存的名字
* @return
*/
public static String uploadInputStream(InputStream inputStream, String path, String filename) throws QiniuException, UnsupportedEncodingException {
//构造一个带指定 Region 对象的配置类,指定华北区
Configuration cfg = new Configuration(Region.region1());
//...其他参数参考类注释
UploadManager uploadManager = new UploadManager(cfg);
// String key = null;
Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
String upToken = auth.uploadToken(BUCKET);
//默认不指定key的情况下,以文件内容的hash值作为文件名
Response response = uploadManager.put(inputStream, String.format("%s/%s", path, filename), upToken, null, null);
log.debug("uploadInputStream response:{}", response.bodyString());
DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
log.debug("uploadInputStream response key: {}", putRet.key);
log.debug("uploadInputStream response hash: {}", putRet.hash);
return getDownloadUrl(path, filename);
}
/**
* 利用七牛云获取下载链接
*
* @param path 文件路径
* @param filename 文件名称
* @return
* @throws UnsupportedEncodingException
*/
public static String getDownloadUrl(String path, String filename) throws UnsupportedEncodingException {
String encodedFileName = URLEncoder.encode(String.format("%s/%s", path, filename), "utf-8").replace("+", "%20");
String publicUrl = String.format("%s/%s", DOMAIN_BUCKET, encodedFileName);
Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
//1小时,可以自定义链接过期时间
return auth.privateDownloadUrl(publicUrl, 60 * 60);
}
/**
* 下载七牛云到指定文件中
* @param path 七牛云中的路径
* @param filename 七牛云中的文件名称
* @param outputFile 输出到指定的文件
* @throws IOException
*/
public static void download(String path, String filename, String outputFile) throws IOException {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(getDownloadUrl(path, filename)).build();
okhttp3.Response response = client.newCall(request).execute();
InputStream in = null;
FileOutputStream outputStream = null;
try {
if (response.isSuccessful()) {
ResponseBody body = response.body();
in = body.byteStream();
outputStream = new FileOutputStream(outputFile);
IOUtils.copy(in, outputStream);
}
} finally {
if (null != in) {
in.close();
}
if (null != outputStream){
outputStream.close();
}
}
}
public static void main(String[] args) throws UnsupportedEncodingException {
//上传字节流
// try {
// InputStream in = new FileInputStream("D:/qiniuyun.txt");
// String url = uploadInputStream(in, "test", "qiniuyun5");
// System.out.println(url);
// } catch (FileNotFoundException | QiniuException e) {
// e.printStackTrace();
// }
//上传文件
// try {
// String url = uploadLocalFile("D:/qiniuyun.txt", "test", "qiniuyun4");
// System.out.println(url);
// } catch (QiniuException e) {
// e.printStackTrace();
// }
//获取下载链接
// String download = getDownloadUrl("test", "qiniuyun4");
// System.err.println(download);
//访问链接地址,将输入流写入到文件
// try {
// download("test", "qiniuyun4", "D:/qiniuyun4.txt");
// } catch (IOException e) {
// e.printStackTrace();
// }
}
}