java后台上传图片/文件到七牛云 古城微笑少年丶 2022-05-16 01:59 206阅读 0赞 准备工作。 一、如果你还没有开启对象存储,请移步到此:[https://blog.csdn.net/Tomwildboar/article/details/81632859][https_blog.csdn.net_Tomwildboar_article_details_81632859] 二、完成测试需要的jar包:[https://download.csdn.net/download/tomwildboar/10602831][https_download.csdn.net_download_tomwildboar_10602831] **项目结构:(至于你创建java项目还是web项目都一样的)** **![watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L1RvbXdpbGRib2Fy_size_16_color_FFFFFF_t_70][]** **upload上传代码:** package test.test; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.util.UUID; import org.junit.Test; import com.google.gson.Gson; import com.qiniu.common.QiniuException; import com.qiniu.common.Zone; import com.qiniu.http.Response; import com.qiniu.storage.Configuration; import com.qiniu.storage.UploadManager; import com.qiniu.storage.model.DefaultPutRet; import com.qiniu.util.Auth; public class Upload { @Test public void aaa(){ //创建一个文件流 File file = new File("d:\\01.jpg"); InputStream stream = null; try { stream = new FileInputStream(file); } catch (FileNotFoundException e) { e.printStackTrace(); } //构造一个带指定Zone对象的配置类 Configuration cfg = new Configuration(Zone.zone0()); //...其他参数参考类注释 UploadManager uploadManager = new UploadManager(cfg); //...生成上传凭证,然后准备上传 String accessKey = "填写你的AK"; String secretKey = "填写你的SK"; String bucket = "填写你的空间名"; //默认不指定key的情况下,以文件内容的hash值作为文件名 String key = UUID.randomUUID().toString().replaceAll("\\-", ""); try { Auth auth = Auth.create(accessKey, secretKey); String upToken = auth.uploadToken(bucket); try { Response response = uploadManager.put(stream,key,upToken,null, null); //解析上传成功的结果 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 } } } catch (Exception ex) { //ignore } } } 代码亲测有效。 上面的代码你需要改变的。 1、在你的D盘下准备一个 01.jpg的文件 2、 String accessKey = "填写你的AK"; String secretKey = "填写你的SK"; String bucket = "填写你的空间名"; 这几个地方填写你自己的 [https_blog.csdn.net_Tomwildboar_article_details_81632859]: https://blog.csdn.net/Tomwildboar/article/details/81632859 [https_download.csdn.net_download_tomwildboar_10602831]: https://download.csdn.net/download/tomwildboar/10602831 [watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L1RvbXdpbGRib2Fy_size_16_color_FFFFFF_t_70]: /images/20220516/9f5282ee5c2b42e287ed987008a17ea4.png
还没有评论,来说两句吧...