|
| 1 | +import com.qiniu.common.QiniuException; |
| 2 | +import com.qiniu.http.Response; |
| 3 | +import com.qiniu.storage.Configuration; |
| 4 | +import com.qiniu.storage.Region; |
| 5 | +import com.qiniu.storage.UploadManager; |
| 6 | +import com.qiniu.util.Auth; |
| 7 | +import com.qiniu.util.StringMap; |
| 8 | + |
| 9 | + |
| 10 | +public class UploadBySelfDefiningParam { |
| 11 | + |
| 12 | + private static final String ACCESS_KEY = "设置好你们自己的AK"; |
| 13 | + private static final String SECRET_KEY = "设置好你们自己的SK"; |
| 14 | + private static final Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY); |
| 15 | + |
| 16 | + private Configuration cfg; |
| 17 | + private UploadManager uploadManager; |
| 18 | + private Region region; |
| 19 | + private String bucket; |
| 20 | + |
| 21 | + { |
| 22 | + bucket = "设置你们自己的上传空间名称"; |
| 23 | + //指定存储空间所在区域,华北region1,华南region2 ,华东 region0 |
| 24 | + region = Region.region1(); |
| 25 | + //初始化cfg实例,可以指定上传区域,也可以创建无参实例 , cfg = new Configuration(); |
| 26 | + cfg = new Configuration(region); |
| 27 | + //是否指定https上传,默认true |
| 28 | + //cfg.useHttpsDomains=false; |
| 29 | + //构建 uploadManager 实例 |
| 30 | + uploadManager = new UploadManager(cfg); |
| 31 | + } |
| 32 | + |
| 33 | + public static void main(String args[]) throws Exception { |
| 34 | + UploadBySelfDefiningParam up = new UploadBySelfDefiningParam(); |
| 35 | + up.upload(); |
| 36 | + } |
| 37 | + |
| 38 | + public void upload() throws QiniuException { |
| 39 | + //设置上传后的文件名称 |
| 40 | + String key = "qiniu_test.jpg"; |
| 41 | + //上传策略 |
| 42 | + StringMap policy = new StringMap(); |
| 43 | + //自定义上传后返回内容,返回自定义参数,需要设置 x:参数名称 |
| 44 | + policy.put("returnBody", "{\"key\":\"$(key)\",\"hash\":\"$(etag)\",\"fname\":\"$(x:fname)\",\"age\",$(x:age)}"); |
| 45 | + //生成上传token |
| 46 | + String upToken = auth.uploadToken(bucket, key, 3600, policy); |
| 47 | + |
| 48 | + //上传自定义参数,自定义参数名称需要以 x:开头 |
| 49 | + StringMap params = new StringMap(); |
| 50 | + params.put("x:fname","123.jpg"); |
| 51 | + params.put("x:age",20); |
| 52 | + String localFilePath = "/Users/mini/Downloads/qiniu_test.jpg"; |
| 53 | + |
| 54 | + Response response = uploadManager.put(localFilePath, key, upToken,params,null,false); |
| 55 | + //输出返回结果 |
| 56 | + System.out.println(response.bodyString()); |
| 57 | + } |
| 58 | + |
| 59 | +} |
0 commit comments