服务端直传是指客户利用服务端SDK从服务端直接上传文件到,交互的双方一般都在机房里面,所以服务端可以自己生成上传凭证,然后利用SDK中的上传逻辑进行上传,最后从获取上传的结果,这个过程中由于双方都是业务服务器,所以很少利用到上传回调的功能,而是直接自定义returnBody
来获取自定义的回复内容。
//构造一个带指定 Region 对象的配置类
Configuration cfg = new Configuration(Region.region0());
UploadManager uploadManager = new UploadManager(cfg);
//...生成上传凭证,然后准备上传
String accessKey = "your access key";
String secretKey = "your secret key";
String bucket = "your bucket name";
//如果是Windows情况下,格式是 D:\\qiniu\\test.png
String localFilePath = "/home/qiniu/test.png";
//默认不指定key的情况下,以文件内容的hash值作为文件名
String key = "covers/test.png";
Auth auth = Auth.create(accessKey, secretKey);
String upToken = auth.uploadToken(bucket);
try {
Response response = uploadManager.put(localFilePath, 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) {
//ignore
}
}
下载远程图片在上传到七牛云服务器
void downloadImage(String type, String id) throws IOException {
File dir = new File("images", type);
dir.mkdirs();
File file = new File(dir, id + ".jpg");
InputStream is;
if (!file.exists()) {
String url = "https://wx" + (random.nextInt(4) + 1) + ".sinaimg.cn/" + type + "/" + id + ".jpg";
if (file.createNewFile()) {
is = HttpUtils.getImage(url);
OutputStream os = new FileOutputStream(file);
try {
IOUtils.copy(is, os);
} finally {
IOUtils.closeQuietly(is);
IOUtils.closeQuietly(os);
}
uploadImage(type, id, file);
}
}
}
void uploadImage(String type, String id, File file) {
Configuration cfg = new Configuration(Region.region0());
UploadManager uploadManager = new UploadManager(cfg);
Auth auth = Auth.create(qiniuProperties.accessKey, qiniuProperties.secretKey);
String upToken = auth.uploadToken(qiniuProperties.bucket);
String key = type + "/" + id;
try {
Response response = uploadManager.put(file, key, upToken);
if (!response.isOK()) {
log.warn("上传图片{}失败: {}", key, response.error);
} else {
log.info("上传图片{}成功", key);
}
} catch (QiniuException e) {
throw new RuntimeException("上传图片失败", e);
}
}