pom.xml
<!-- 文件上传到云服务器 -->
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.14.2</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.qiniu</groupId>
<artifactId>happy-dns-java</artifactId>
<version>0.1.6</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.qiniu</groupId>
<artifactId>qiniu-java-sdk</artifactId>
<version>[7.3.0, 7.3.99]</version>
</dependency>
QiNiuUtil .java
package com.demo;
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 java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
public class QiNiuUtil {
private static String accessKey = ""; // accessKey
private static String secretKey = ""; // secretKey
private static String bucket = ""; // 空间名字
private static final String PATH = "C:\\upload\\";// 当前静态资源目录
public String uploadToQiNiu(String fileName) {
Configuration cfg = new Configuration(Region.region2()); // 东南区
UploadManager uploadManager = new UploadManager(cfg);
String newUrl = "http://cdn.xiaofeia.top/"; // 你的cdn域名地址(需要配置CNAME, 也就是你的二级域名指向七牛云的域名.)
Auth auth = Auth.create(accessKey, secretKey);
String upToken = auth.uploadToken(bucket, fileName); // 覆盖式上传
try {
Response response = uploadManager.put(PATH + fileName, fileName, upToken);
DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
newUrl += fileName == null ? putRet.key : fileName;
} catch (QiniuException ex) {
Response r = ex.response;
System.err.println(r.toString());
try {
System.err.println(r.bodyString());
} catch (QiniuException ex2) {
// ignore
}
}
return newUrl;
}
private static void FileFilter(File dir, ArrayList<File> arrayList) {
File[] list = dir.listFiles(new FileFilter() {
@Override
public boolean accept(File pathName) {
if (pathName.isFile()) {
return true;
} else if (pathName.isDirectory() && !pathName.isHidden()) {
FileFilter(pathName, arrayList);
}
return false;
}
});
for (File file : list) {
arrayList.add(file);
}
}
public static void main(String[] args) {
// 把js目录中所有的文件存到空间中;
File file = new File(PATH + "js");
ArrayList<File> list = new ArrayList<>();
FileFilter(file, list);
for (File file1 : list) {
// 上传到七牛云的文件名, 按照目录结构来 (js/jquery/jquery.js)
String path = file1.getAbsolutePath().replace(PATH, "").replace("\\", "/");
System.out.println(path);
// 获取上传到七牛云的全路径(http://域名 + js/jquery/jquery.js)
String realPath = new QiNiuUtil().uploadToQiNiu(path);
System.out.println(realPath);
}
System.out.println("上传完毕提醒唷");
}
}
偷偷的把自己的资源走了cdn.服务器的压力又小了…哈哈哈
看完点个赞呗?O(∩_∩)O~