1、前端
var formData = new FormData(); formData.append(‘file‘, $("#file").val()); $.ajax({ url:‘地址‘, type:‘post‘, data:formData, async:false, processData:false, contentType:false, success:function (response) { alert(response.msg); } })
2、controller
// 创建一个通用的多部分解析器 CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(); MultipartHttpServletRequest multiRequest = commonsMultipartResolver.resolveMultipart((HttpServletRequest) request);
List<String> strList = new ArrayList<String>(); String fileName = null; List<MultipartFile> files = request.getMultiFileMap().get("file"); if(files != null) { for (MultipartFile file : files){ String myFileName = file.getOriginalFilename(); if (myFileName.trim() != ""){ // 获得图片的原始名称 String originalFilename = file.getOriginalFilename(); // 获得图片后缀名称 String suffix = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase(); // 获得上传路径的绝对路径地址 String realPath = request.getSession().getServletContext().getRealPath(路径); File realPathDirectory = new File(realPath); if (realPathDirectory == null || !realPathDirectory.exists()){ realPathDirectory.mkdirs(); } // 采用UUID的方式重命名上传后的文件名 fileName = java.util.UUID.randomUUID().toString() + suffix; File uploadFile = new File(realPathDirectory + "/" + fileName); file.transferTo(uploadFile); strList.add(request.getContextPath() + "/" + DirectoryName + fileName); } }}
原文地址:https://www.cnblogs.com/wsfu/p/10750762.html
时间: 2024-10-11 12:31:06