版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/shenzhen_zsw/article/details/89369053
项目中文件上传分析
需求简述:
项目中用户注册,需要上传用户头像信息,可以选择多个,进行上传;
User
package com.mooc.house.common.model;
import java.util.Date;
import org.springframework.web.multipart.MultipartFile;
public class User {
private Long id;
private String email;
private String phone;
private String name;
private String passwd;
private String confirmPasswd;
private Integer type; // 普通用户1,经纪人2
private Date createTime;
private Integer enable;
private String avatar;
private MultipartFile avatarFile;
private String newPassword;
private String key;
private Long agencyId;
private String aboutme;
private String agencyName;
......
}
说明:
1)注意private MultipartFile avatarFile;此字段,用来传输文件的;
UserController
package com.mooc.house.web.controller;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import com.mooc.house.biz.service.AgencyService;
import com.mooc.house.biz.service.UserService;
import com.mooc.house.common.constants.CommonConstants;
import com.mooc.house.common.model.User;
import com.mooc.house.common.result.ResultMsg;
import com.mooc.house.common.utils.HashUtils;
@Controller
public class UserController {
@Autowired
private UserService userService;
@Autowired
private AgencyService agencyService;
/**
* 注册提交:1.注册验证 2 发送邮件 3验证失败重定向到注册页面 注册页获取:根据account对象为依据判断是否注册页获取请求
*
* @param account
* @param modelMap
* @return
*/
@RequestMapping("accounts/register")
public String accountsRegister(User account, ModelMap modelMap) {
if (account == null || account.getName() == null) {
modelMap.put("agencyList", agencyService.getAllAgency());
return "/user/accounts/register";
}
// 用户验证
ResultMsg resultMsg = UserHelper.validate(account);
if (resultMsg.isSuccess() && userService.addAccount(account)) {
modelMap.put("email", account.getEmail());
return "/user/accounts/registerSubmit";
} else {
return "redirect:/accounts/register?" + resultMsg.asUrlParams();
}
}
}
说明:
1)account为User对象,包含上传文件对象;
2)添加用户userService.addAccount(account)
UserService
package com.mooc.house.biz.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.google.common.collect.Lists;
import com.mooc.house.biz.mapper.UserMapper;
import com.mooc.house.common.model.User;
import com.mooc.house.common.utils.BeanHelper;
import com.mooc.house.common.utils.HashUtils;
@Service
public class UserService {
@Autowired
private FileService fileService;
@Autowired
private MailService mailService;
@Autowired
private UserMapper userMapper;
@Value("${file.prefix}")
private String imgPrefix;
public List<User> getUsers() {
return userMapper.selectUsers();
}
/**
* 1.插入数据库,非激活;密码加盐md5;保存头像文件到本地 2.生成key,绑定email 3.发送邮件给用户
*
* @param account
* @return
*/
@Transactional(rollbackFor = Exception.class)
public boolean addAccount(User account) {
account.setPasswd(HashUtils.encryPassword(account.getPasswd()));
List<String> imgList = fileService.getImgPaths(Lists.newArrayList(account.getAvatarFile())); // 上传文件
if (!imgList.isEmpty()) {
account.setAvatar(imgList.get(0));
}
BeanHelper.setDefaultProp(account, User.class);
BeanHelper.onInsert(account);
account.setEnable(0);
userMapper.insert(account);
mailService.registerNotify(account.getEmail()); // 发送邮件
return true;
}
......
}
说明:
1)此方法用来上传文件,fileService.getImgPaths(Lists.newArrayList(account.getAvatarFile())); // 上传文件
FileService
package com.mooc.house.biz.service;
import java.io.File;
import java.io.IOException;
import java.time.Instant;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.io.Files;
@Service
public class FileService {
@Value("${file.path:}")
private String filePath;
public List<String> getImgPaths(List<MultipartFile> files) {
if (Strings.isNullOrEmpty(filePath)) {
filePath = getResourcePath();
}
List<String> paths = Lists.newArrayList();
files.forEach(file -> {
File localFile = null;
if (!file.isEmpty()) {
try {
localFile = saveToLocal(file, filePath);
String path = StringUtils.substringAfterLast(localFile.getAbsolutePath(), filePath);
paths.add(path);
} catch (IOException e) {
throw new IllegalArgumentException(e);
}
}
});
return paths;
}
public static String getResourcePath(){
File file = new File(".");
String absolutePath = file.getAbsolutePath();
return absolutePath;
}
private File saveToLocal(MultipartFile file, String filePath2) throws IOException {
File newFile = new File(filePath + "/" + Instant.now().getEpochSecond() +"/"+file.getOriginalFilename());
if (!newFile.exists()) {
newFile.getParentFile().mkdirs();
newFile.createNewFile();
}
Files.write(file.getBytes(), newFile);
return newFile;
}
}
说明:
1)将文件存储到制定位置localFile = saveToLocal(file, filePath);
2)在application.properties中配置上传文件路径;file.path=/Users/wangjialuo/opt/imgs;