1.html
<button style="margin-top: 20px;margin-left: 20px" type="button" class="layui-btn" id="upload"> <i class="layui-icon"></i>上传封面图 </button>
2.js
layui.use('upload', function () { var $ = layui.jquery , upload = layui.upload; //普通图片上传 var uploadInst = upload.render({ elem: '#upload' , url: '/admin/upload_img' , choose: function (obj) { //预览本地文件示例 obj.preview(function (index, file, result) { // console.log(result); $('#picture').attr('src', result).attr('width', '80px').attr('hight', '80px'); }); } , data: {} , size: 1024 //限制文件大小,单位 KB , auto: true //自动上传 如果需要绑定上传 则需要设置为false //,multiple: true //多文件 // , bindAction: '#update' //绑定上传按钮 , done: function (res) { //console.log(res); if (res.code == 1) { //上传成功 layer.msg('上传成功,请勿刷新页面'); imgid = res.data.src; } else { return layer.msg('上传失败'); } } }) });
3.后台逻辑
@RequestMapping("/upload_img") public @ResponseBody String uploadImg(@RequestParam("file") MultipartFile file,HttpServletResponse response) { response.setHeader("Access-Control-Allow-Origin", "*"); return articleService.uploadImg(file); }
public String uploadImg(MultipartFile file) { String str = ""; if (null != file) { //生成uuid作为文件名称 String uuid = UUID.randomUUID().toString().replaceAll("-", ""); System.out.println("文件名称:" + uuid); //获得文件类型(判断如果不是图片文件类型,则禁止上传) String contentType = file.getContentType(); System.out.println("文件类型:" + contentType); //获得文件后缀名称 String imageName = contentType.substring(contentType.indexOf("/") + 1); System.out.println("文件后缀名称:" + imageName); String filePath = UPLOAD_FILE_PATH; //如果不存在,则创建新文件夹 File f = new File(filePath); if (!f.exists()) { f.mkdirs(); } //新生成的文件名称 String fileName = uuid + "." + imageName; System.out.println("新生成的文件名称:" + fileName); //图片保存的完整路径 String pathName = filePath + "/img/" + fileName; System.out.println(pathName); //复制操作 //将图片从源位置复制到目标位置 try { file.transferTo(new File(pathName)); } catch (IOException e) { e.printStackTrace(); } str = "{\"code\": 1,\"msg\": \"success\",\"data\": {\"src\":\"/img/" + fileName + "\"}}"; } else { System.out.println("文件为空"); } return str; }