直接上完整代码
/**
* 文件上传
*/
public class fileUpload {
@Autowired
ServletContext context;
@Autowired
private Upload_pubMapper upload_pubMapper;
/**
* 文件上传至服务器指定目录下
* 文件信息(原始文件名、用id替换后的文件名、文件相对路径(地址)、后缀)存入附件表中
* 返回文件id存入主表
* 扩充:查询时用附件id关联附件表,返回文件名以及文件相对地址,即可满足前端页面点击下载的功能
* @param request
* @param response
* @param id 主表id(为哪条数据上传文件)
* @param file MultipartFile类型文件
* @return map 返回上传成功标识
* @throws Exception
*/
public Map upload(HttpServletRequest request, HttpServletResponse response, String id,MultipartFile file)throws Exception {
Map<String,String> map = new HashMap<String, String>();
try {
if (file != null && file.getOriginalFilename() != null && !file.getOriginalFilename().equals("")) {
String fjid = SnowIdUtil.snowIdUtil.nextId();
Upload_pubPage uploadPage = new Upload_pubPage(); // 附件表实体
uploadPage.setId(fjid);
String xsm=file.getOriginalFilename(); // 获取文件名(含后缀)
String wjlx=xsm.substring(xsm.lastIndexOf(".")+1); // 获取文件后缀
String ccm=uploadPage.getId()+"."+wjlx; // 更改文件名称,用id替代(防止重名)
// 附件信息给附件表实体赋值
uploadPage.setXsm(xsm);
uploadPage.setCcm(ccm);
uploadPage.setWjlx(wjlx);
//保存的文件名
String dFileName = uploadPage.getCcm();
//保存路径
//springboot 默认情况下只能加载 resource文件夹下静态资源文件
//生成保存文件
String savePath = "upload/pub/";
String realPath = context.getRealPath("/"); //实际路径
String dz = realPath + "/" + savePath + dFileName;
File uploadFile = new File(dz);
if (!uploadFile.exists()) {
uploadFile.getParentFile().mkdirs(); // 创建pub文件夹
uploadFile.createNewFile(); // 创建文件
}
file.transferTo(uploadFile); // 保存文件
uploadPage.setWllj(savePath + uploadPage.getCcm()); // 文件的相对路径
// 将附件信息存入附件表
upload_pubMapper.uploadFirst(uploadPage);
// 更新主表的附件id(此处省略)
map.put("jg","1");
map.put("message", "上传成功");
} else {
map.put("jg","-1");
map.put("message", "上传失败,请选择文件");
}
} catch (Exception e) {
e.printStackTrace();
map.put("jg","-1");
map.put("message", "上传失败"+e.getMessage());
}
return map;
}
}