前言
在 SSM(Spring + Spring MVC + MyBatis)项目中,文件上传是常见需求。要实现这一功能,除了后端控制器的逻辑处理外,还需要确保 Spring 容器正确配置了 multipartResolver,否则 MultipartFile 参数无法被解析。
前端准备
前端表单必须设置正确的 enctype 属性,否则文件流无法传输。以下是一个简单的文件输入控件示例:
<input type="file" name="file" id="input_file" required="required" style="display:inline;">
注意:实际开发中建议限制文件大小和类型,并提示用户推荐尺寸,例如 500 * 500 像素。
后端实现
后端核心在于处理 MultipartFile 对象,将其保存到服务器磁盘,并将相对路径存入数据库。下面以 AdminController 为例,展示完整的上传逻辑。
关键步骤解析
- 获取物理路径:通过 ServletContext 获取项目的真实根路径,拼接上传目录。
- 目录管理:按日期创建子文件夹,避免文件堆积在同一目录下,便于维护。
- 文件名处理:使用 UUID 结合原文件名后缀,解决同名覆盖问题。
- 数据持久化:将生成的相对路径设置到实体对象中,调用 Service 层保存。
代码示例
package com.hopu.controller;
import com.github.pagehelper.PageInfo;
import com.hopu.bean.Admins;
import com.hopu.bean.Goods;
import com.hopu.bean.PageBean;
import com.hopu.service.AdminService;
import com.hopu.util.UUIDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
java.io.File;
java.io.IOException;
java.text.SimpleDateFormat;
java.util.Date;
java.util.List;
{
AdminService adminService;
String IOException {
System.out.println(goods);
request.getSession().getServletContext().getRealPath();
System.out.println( + realPath);
();
sdf.format( ());
System.out.println( + dateFile);
realPath = realPath + + dateFile;
(realPath);
(!uploadDir.exists()) {
uploadDir.mkdirs();
}
file.getOriginalFilename();
UUIDUtil.getUUID() + str.substring(str.lastIndexOf());
(uploadDir, name);
file.transferTo(upFile);
+ dateFile + + name;
goods.setCover(cover);
System.out.println( + goods);
adminService.uploadadd(goods);
;
}
}

