用JAVA实现后端文件上传接口,上传到七牛云
时间: 2023-01-12 17:22:01 浏览: 210
首先,您需要安装七牛云 Java SDK,可以使用以下命令安装:
```
$ mvn install com.qiniu:qiniu-java-sdk:7.2.14
```
然后,您可以使用以下代码实现后端文件上传接口:
```java
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.FileInputStream;
import java.io.IOException;
import java.util.Properties;
public class FileUploader {
private static final String ACCESS_KEY;
private static final String SECRET_KEY;
private static final String BUCKET;
private static final String DOMAIN;
static {
Properties prop = new Properties();
try {
prop.load(new FileInputStream("config.properties"));
} catch (IOException e) {
e.printStackTrace();
}
ACCESS_KEY = prop.getProperty("ACCESS_KEY");
SECRET_KEY = prop.getProperty("SECRET_KEY");
BUCKET = prop.getProperty("BUCKET");
DOMAIN = prop.getProperty("DOMAIN");
}
public static String upload(String filePath) {
// 构造一个带指定 Region 对象的配置类
Configuration cfg = new Configuration(Region.region2());
// 其他参数参考类注释
UploadManager uploadManager = new UploadManager(cfg);
// 生成上传凭证,然后准备上传
Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
String upToken = auth.uploadToken(BUCKET);
try {
Response response = uploadManager.put(filePath, null, upToken);
// 解析上传成功的结果
DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
return DOMAIN + "/" + putRet.key;
} catch (QiniuException ex) {
Response r = ex.response;
System.err.println(r.toString());
try {
System.err.println(r.bodyString());
} catch (QiniuException ex2) {
// ignore
}
return null;
}
}
}
```
在上
阅读全文