之前用ssm写的
https://my.oschina.net/springMVCAndspring/blog/1821045
https://my.oschina.net/springMVCAndspring/blog/1821209
1.效果
2.实现过程
2.1 前端
<form method="post" action="/upload" enctype="multipart/form-data"> <input type="file" name="file"><br> <input type="text" id="14a" name="name" value="zs"> <input type="password" id="14111a" name="password" value="22"> <input type="submit" value="提交"> </form>
2.2 后台
(1) 设置上传文件大小
# 上传文件总的最大值 spring.servlet.multipart.max-request-size=1MB # 单个文件的最大值 spring.servlet.multipart.max-file-size=1MB
(2) controller层
(3) 上传工具类
package cn.ma.mylife.utils; import com.alibaba.fastjson.JSON; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.UUID; /** * @company: 马氏集团 * @FillName:updloadUtils * @author: sunshine * @date: 2019/11/1 20:43 * @description: 单个文件上传及删除 */ public class fileUtils { /** * @author: sunshine * @description:1.单个附件上传 * Path:保存位置(必) * @date 2019/11/2 11:33 * @param: file:文件对象(必) * @url: * @return: **/ public static String uploadFile(MultipartFile file, String Path) { HashMap<String, Object> map = new HashMap<>(); if (file.isEmpty()) { map.put("msg", "上传失败,请选择文件"); return JSON.toJSONString(map); } //得到文件的后缀名称 String getFilename = file.getOriginalFilename(); int index = getFilename.lastIndexOf("."); char[] ch = getFilename.toCharArray(); //根据 copyValueOf(char[] data, int offset, int count) 取得最后一个字符串 String lastString = String.copyValueOf(ch, index + 1, ch.length - index - 1); String filePath = Path + UUID.randomUUID().toString().replace("-", "") + "." + lastString; File dest = new File(filePath); try { file.transferTo(dest); System.out.println("上传成功"); map.put("msg", "success"); map.put("url", dest); return JSON.toJSONString(map); } catch (IOException e) { map.put("msg", "fail!"); System.out.println(e.getMessage()); } return JSON.toJSONString(map); } /** * @author: sunshine * @description: 2.附件删除 * @date 2019/11/2 11:32 * @param: fileName:文件所在位置(必) * @url: * @return: **/ public static boolean deleteFile(String fileName) { File file = new File(fileName); if (file.isFile() && file.exists()) { file.delete(); System.out.println("删除单个文件" + fileName + "成功!"); return true; } else { System.out.println("删除单个文件" + fileName + "失败!"); return false; } } }