前端
<form action="/file/fileupload" method="post" enctype="multipart/form-data"> <label>文件上传</label> <input type="file" name="file"> <input type="submit" value="提交"> </form>
后端
import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; @Controller @RequestMapping("/file") public class FileUploadUtils { @RequestMapping("/fileupload") public @ResponseBody String upload(MultipartFile file, HttpServletRequest request) throws IOException { SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSS"); String res = sdf.format(new Date()); // uploads文件夹位置 String rootPath = request.getSession().getServletContext().getRealPath("resource/uploads/"); // 原始名称 String originalFileName = file.getOriginalFilename(); // 新文件名 // String newFileName = "sliver" + res + originalFileName.substring(originalFileName.lastIndexOf(".")); String newFileName = "sliver" +originalFileName; System.out.println("============================测试开始============================="); System.out.println("request.getSession()=" + request.getSession()); System.out.println("request.getSession().getServletContext()=" + request.getSession().getServletContext()); System.out.println("request.getSession().getServletContext().getRealPath(\"resource/uploads/\")=" + request.getSession().getServletContext().getRealPath("resource/uploads/")); System.out.println("原始文件名称:" + originalFileName);
//插入数据库 // BaseInformationAttachment attachment = new BaseInformationAttachment(); // attachment.setId(UUID.randomUUID().toString()); // attachment.setAttachmentRealName(originalFileName); // attachment.setAttachmentPath(rootPath + originalFileName); // System.out.println("实际路径:" + (rootPath + originalFileName)); // service.insert(attachment);
System.out.println("============================测试结束============================="); // 创建年月文件夹 Calendar date = Calendar.getInstance(); File dateDirs = new File(date.get(Calendar.YEAR) + File.separator + (date.get(Calendar.MONTH)+1)); // 新文件 File newFile = new File(rootPath + File.separator + dateDirs + File.separator + newFileName); // 判断目标文件所在目录是否存在 if( !newFile.getParentFile().exists()) { // 如果目标文件所在的目录不存在,则创建父目录 newFile.getParentFile().mkdirs(); } System.out.println(newFile); // 将内存中的数据写入磁盘 file.transferTo(newFile); // 完整的url String fileUrl = date.get(Calendar.YEAR) + "/" + (date.get(Calendar.MONTH)+1) + "/" + newFileName; return fileUrl; } }