在大学时期做的一个电影项目,使用了文件上传功能,当时是在本地创建了一个虚拟路径,用来存储文件,当然,也可以使用服务器的路径,用于将文件上传到服务器中存储。上一篇文章上传文件功能的实现是将文件以字节流的形式存储进数据库中,数据库中需要有一个字段专门存储数据。本篇,由于是将文件上传到指定路径,所以只需要存入数据库文件所在位置即可。
创建一个虚拟路径
创建虚拟路径主要是为了文件读取时候可以从这个路径读取到,我将F盘下的upload文件夹下的film2文件夹作为虚拟路径
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/*
静态资源配置文件
以后考虑到前后端分离还会使用其他配置,比如跨域
* */
@Configuration
@EnableWebMvc
public class StaticResourceConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//将static设置为静态资源
registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
//访问到虚拟路径
registry.addResourceHandler("/resources/**")
.addResourceLocations("file:F:/upload/film2/");
}
}
数据库字段
实体类
import org.springframework.format.annotation.DateTimeFormat;
import java.io.Serializable;
import java.util.Date;
public class User implements Serializable {
private int userId;//用户编号
private String userName;//用户名
private String pwd;//密码
private String sex;//性别
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date birth;//生日
private int role;//角色
private int state;//状态 1 可用 2 禁用
private double balance;//账户余额
private String userImage;//用户头像
private int score;//积分
private String phone;//电话
public User() {
}
public User(int userId, String userName, String pwd, String sex, Date birth, int role, int state, double balance, String userImage, int score, String phone) {
this.userId = userId;
this.userName = userName;
this.pwd = pwd;
this.sex = sex;
this.birth = birth;
this.role = role;
this.state = state;
this.balance = balance;
this.userImage = userImage;
this.score = score;
this.phone = phone;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
public int getRole() {
return role;
}
public void setRole(int role) {
this.role = role;
}
public int getState() {
return state;
}
public void setState(int state) {
this.state = state;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
public String getUserImage() {
return userImage;
}
public void setUserImage(String userImage) {
this.userImage = userImage;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
@Override
public String toString() {
return "User{" +
"userId=" + userId +
", userName='" + userName + '\'' +
", pwd='" + pwd + '\'' +
", sex='" + sex + '\'' +
", birth=" + birth +
", role=" + role +
", state=" + state +
", balance=" + balance +
", userImage='" + userImage + '\'' +
", score=" + score +
", phone='" + phone + '\'' +
'}';
}
}
controller接口(想当初我刚学代码的时候这个注释写的又多又详细,新手小白也可以看懂我的代码,现在就没有当初那么细致了。。。)
//管理员添加用户
@RequestMapping("/addUser")
public ModelAndView upload1(ModelAndView mav, MultipartFile file, User user) throws Exception{
//如何解析file
if (file.isEmpty()){
mav.addObject("uploading","文件为空");
}
else {
//进行文件上传
//文件名获取
String fileName=file.getOriginalFilename();
//文件名后缀
String suffixName=fileName.substring(fileName.lastIndexOf('.'));
//上传地址
String filePath="F://upload//film2//image//"; //地址使用//结尾
//考虑到文件名有可能重复,最好重构文件名 防止图片文件名乱码、防止重复
fileName= UUID.randomUUID()+suffixName;
// System.out.println("重构文件名:"+fileName);
//生成文件地址
File dest=new File(filePath+fileName);
//判断filePath是否存在 不在则创建
if (dest.getParentFile().exists()){
dest.getParentFile().mkdirs();
}
//文件上传
try{
file.transferTo(dest);
user.setUserImage(fileName);
boolean result= adminService.addUser(user);
if (result){
mav.setViewName("admin/main2");
}else {
mav.setViewName("admin/main2");
}
}catch (IOException e){
e.printStackTrace();
}
}
return mav;
}
其中,与之前以字节流存储进数据库对比,这边由于所有文件都存入同一个文件夹中,为了防止重复,使用UUID来更名,而且对于路径地址的定义需要用到//分割且用//结尾
补充:上传的文件可能过大不允许上传,那么就可以在配置文件中设置一下允许上传的文件大小
至此,文件就可以上传到指定目录下存储,当前端需要查看的时候,只需要查询这个文件存储在数据库中的路径,就可以用image标签进行展示。
版权声明:本文为qq_47770103原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。