SpringBoot上传图片
一、上传单个图片
1、前端发送请求,后端解析图片,上传成功后返回一个数据库保存的图片地址
package com.donleo.stmg.common; import com.donleo.stmg.common.api.CommonResult; import com.donleo.stmg.utils.CommonPath; import org.springframework.util.Assert; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.List; /** * @author liangd * date 2020-11-24 18:32 * code 图片上传接口 */ @RestController @RequestMapping("/upload") public class UploadController { @PostMapping("/img") public CommonResult uploadFile(@RequestParam("file") MultipartFile file) { if (file.isEmpty()) { return CommonResult.failed("上传失败"); } //文件名称 String fileName = file.getOriginalFilename(); //允许上传文件名的后缀 List<String> FILE_WHILE_EXT_LIST = Arrays.asList("JPG","PNG","JPEG","GIF"); Assert.notNull(fileName,"File name can not be empty"); String fileExtName = fileName.substring(fileName.lastIndexOf(".") + 1); if (FILE_WHILE_EXT_LIST.contains(fileExtName.toUpperCase())){ //上传文件的位置 //SAVE_PATH E:/liangd/Java/stmg-front/src/main/webapp //IMG_PATH /upload/ String filePath = CommonPath.SAVE_PATH.getValue() + CommonPath.IMG_PATH.getValue(); //全路径 E:/liangd/Java/stmg-front/src/main/webapp/upload/1.jpg File dest = new File(filePath + fileName); //数据库保存地址 /upload/1.jpg String imgPath = CommonPath.IMG_PATH.getValue() + fileName; try { file.transferTo(dest); return CommonResult.success(imgPath); } catch (IOException e) { return CommonResult.failed("上传失败"); } } return CommonResult.failed("图片格式不正确"); } }
CommonResult是自己封装的公共返回结果集,可以直接返回String类型
2、前端页面
1) html
<!--图片上传--> <div class="layui-form-item"> <button type="button" class="layui-btn layui-input-block" id="avatarImg"> <i class="layui-icon"></i>上传头像 </button> <div class="layui-input-block"> <img src="" width="100px" height="100px" id="priview" style="margin: 5px 0"> <span>图片地址:</span> <input type="text" class="layui-input-block" id="avatar" name="avatar" readonly> </div> </div>
2) js
这里用layUI的上传工具upload.render发送的请求,使用其它工具发送的请求也大同小异
/** * 图片上传 */ upload.render({ elem: '#avatarImg',//绑定元素 headers:HEADERS, url: LOCAL_CROSS_URL + '/upload/img', //请求接口 done: function (reg) { //上传成功回调 if (reg.code === 200) { $('#priview').attr('src', reg.data); $('#avatar').val(reg.data); layer.msg("上传成功", {icon: 1, time: 1000, shade: 0.4}) } else { layer.msg("上传失败", {icon: 5, time: 1000, shade: 0.4}) } }, error: function () { //请求异常回调 } , size: 1024 * 5 //最大5M });
3、页面回显
二、上传多个图片文件
MultipartFile file改为数组形式就可以了
@PostMapping("/img") public CommonResult uploadFile(@RequestParam("file") MultipartFile file[])