以前用ssm寫的前端
https://my.oschina.net/springMVCAndspring/blog/1821045java
https://my.oschina.net/springMVCAndspring/blog/1821209web
<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>
(1) 設置上傳文件大小spring
# 上傳文件總的最大值 spring.servlet.multipart.max-request-size=1MB # 單個文件的最大值 spring.servlet.multipart.max-file-size=1MB
(2) controller層json
(3) 上傳工具類dom
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; } } }