最近在做一个项目,需要用到云存储,项目用的是七牛云。现在将项目过程中关于调用七牛云平台的java api来上传本地文件到七牛云空间的一个简单的demo展示给大家,希望对同样再用七牛云的童鞋们有所帮助。
Java代码:
import org.json.JSONException;
import com.qiniu.api.auth.AuthException;
import com.qiniu.api.auth.digest.Mac;
import com.qiniu.api.io.IoApi;
import com.qiniu.api.io.PutExtra;
import com.qiniu.api.io.PutRet;
import com.qiniu.api.rs.PutPolicy;
public class QiniuUpload {
public static final String ACCESS_KEY = "XXXXXXX"; //你的access_key
public static final String SECRET_KEY = "XXXXXXX"; //你的secret_key
public static final String BUCKET_NAME = "XXXXX"; //你的bucket_name
public static void uploadFile(String filePath, String fileName) {
Mac mac = new Mac(QiniuUpload.ACCESS_KEY,QiniuUpload.SECRET_KEY);
PutPolicy putPolicy = new PutPolicy(QiniuUpload.BUCKET_NAME);
String uptoken = null;
try {
uptoken = putPolicy.token(mac);
} catch (AuthException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(uptoken); //输出上传凭证
PutExtra putExtra = new PutExtra();
PutRet putRet = IoApi.putFile(uptoken, fileName, filePath, putExtra);
System.out.println(putRet.getKey()); //输出上传到七牛云之后的文件名称
}
public static void main(String[] args) {
try {
uploadFile("E:\\text.txt","hello.txt"); //第一个参数是本地文件路径,第二个参数是上传到七牛云之后的文件名称,由你来设定。
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
至少所需要的jar包在附件中。