java上传图片到七牛云
如有需要可以加我Q群【308742428】大家一起讨论技术,有偿提供技术支持。
后面会不定时为大家更新文章,敬请期待。
话不多说直接上代码:
前端这里我是使用的layui的插件,样式还是可以需要引入两个文件:
一个css样式文件,一个js文件
1 2 | < link rel="stylesheet" href="${ctxStatic}/layui/css/layui.css" media="all"> < script src="${ctxStatic}/layui/layui.js" charset="utf-8"></ script > |
html页面样式:
html代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | < div class="row"> < div class="col-xs-12"> < div class="form-group"> < label class="control-label col-sm-2">${text('图片')}:</ label > < div class="col-sm-10"> < div class="layui-upload"> < button type="button" class="layui-btn" id="btn_imgs">< i class="layui-icon"></ i >上传图片</ button > < button type="button" class="layui-btn layui-btn-normal" οnclick="resetimg()" >清空图片</ button > < div class="layui-upload-list"> < blockquote class="layui-elem-quote layui-quote-nm" style="margin-top: 10px;"> < div class="layui-upload-list" id="img_imgs"></ div > </ blockquote > < p id="imgsText"></ p > < input type="hidden" id="img" name="img" value="${zrCircle.img}"> </ div > </ div > </ div > </ div > </ div > </ div > |
javascript代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | //清空图片 function resetimg(){ $( '#img_imgs' ).empty(); $( "#img" ).val( "" ); } layui.use( 'upload' , function (){ var $ = layui.jquery ,upload = layui.upload; //多图片上传 如何只需要上传单张图片multiple,number两个参数去掉即可 upload.render({ elem: '#btn_imgs' ,accept: 'images' ,acceptMime: 'image/*' ,exts: 'jpg|png|jpeg|bmp' ,url: '' //改成您自己的上传接口 ,multiple: true ,number:5 ,before: function (obj){ //预读本地文件示例,不支持ie8 obj.preview( function (index, file, result){ $( '#img_imgs' ).append( '<img src="' + result + '" alt="' + file.name + '" style="margin-left:10px;" class="layui-upload-img" width="200px" height="160px">' ) }); } ,done: function (res){ if (res.code ==500){ return layer.msg( '上传失败' ); } else { //上传成功 var ss=$( "#img" ).val(); if (ss.length>4){ ss=ss+ "," +res.url; } else { ss=res.url; } $( "#img" ).val(ss); //点击放大 renderImg(); } } ,error: function (){ //演示失败状态,并实现重传 var demoText = $( '#imgsText' ); demoText.html( '<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>' ); demoText.find( '.demo-reload' ).on( 'click' , function (){ uploadInst.upload(); }); } }); }); |
后台java代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | /** * 上传图片 * @param file * @return */ @PostMapping (value = "upload" ) @ResponseBody public Map<String,Object> upload(MultipartFile file) { String fileName= null ; Map<String,Object> map= new HashMap<>(); try { File f = File.createTempFile( "tmp" , null ); //通过MultipartFile的transferTo(File dest)这个方法来转存文件到指定的路径。MultipartFile转存后,无法再操作,会报错 file.transferTo(f); fileName = QiniuCloudUtil.upload(f); fileName= "http://qiniu.zenran.com/" +fileName; System.out.println(fileName); //在JVM进程退出的时候删除文件,通常用在临时文件的删除. f.deleteOnExit(); map.put( "code" , 200 ); map.put( "url" ,fileName); } catch (IOException e) { map.put( "code" , 500 ); map.put( "url" ,fileName); e.printStackTrace(); } return map; } |
QiniuCloudUtil工具类:
需要注意使用七牛云需要下载依赖包:
1 2 3 4 5 | <dependency> <groupId>com.qiniu</groupId> <artifactId>qiniu-java-sdk</artifactId> <version>7.2.28</version> </dependency> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | 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.util.Auth; import org.apache.commons.lang3.StringUtils; import java.io.File; import java.io.IOException; import java.util.UUID; /** * @author dsn * @createTime 07 21:07 * @description 七牛云工具 */ public class QiniuCloudUtil { // 设置需要操作的账号的AK和SK private static final String ACCESS_KEY = "" ; private static final String SECRET_KEY = "" ; // 要上传的空间名 private static final String bucketname = "" ; private static final String domain = "" ; //外链域名 // 密钥 private static final Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY); // //上传 public static String upload(File file) throws IOException { // 创建上传对象,Zone*代表地区 Configuration configuration = new Configuration(Zone.zone2()); UploadManager uploadManager = new UploadManager(configuration); try { // 调用put方法上传 String token = auth.uploadToken(bucketname); if (StringUtils.isEmpty(token)) { System.out.println( "未获取到token,请重试!" ); return null ; } String imageName = UUID.randomUUID().toString(); System.out.println( "File name = " +imageName); Response res = uploadManager.put(file,imageName,token); // 打印返回的信息 if (res.isOK()){ return imageName; } } catch (QiniuException e) { Response r = e.response; // 请求失败时打印的异常的信息 e.printStackTrace(); System.out.println( "error " +r.toString()); try { // 响应的文本信息 System.out.println(r.bodyString()); } catch (QiniuException e1) { System.out.println( "error " +e1.error()); } } return null ; } } |
分类:
java
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core内存结构体系(Windows环境)底层原理浅谈
· C# 深度学习:对抗生成网络(GAN)训练头像生成模型
· .NET 适配 HarmonyOS 进展
· .NET 进程 stackoverflow异常后,还可以接收 TCP 连接请求吗?
· SQL Server统计信息更新会被阻塞或引起会话阻塞吗?
· 传国玉玺易主,ai.com竟然跳转到国产AI
· 本地部署 DeepSeek:小白也能轻松搞定!
· 自己如何在本地电脑从零搭建DeepSeek!手把手教学,快来看看! (建议收藏)
· 我们是如何解决abp身上的几个痛点
· 普通人也能轻松掌握的20个DeepSeek高频提示词(2025版)