Springboot(cloud)上传图片
controller层代码:
@RequestMapping("update")
public String update(Model model,Goods goods,HttpServletRequest request,@RequestParam("myfile") MultipartFile file) {
**// 获取文件名
String fileName = file.getOriginalFilename();
String uuidFileName = UUID.randomUUID().toString();
// 过去后缀名
String suffixName = fileName.substring(fileName.lastIndexOf("."));
// 获取项目绝对路径
String realPath = request.getServletContext().getRealPath("/");
// 动态创建目录,防止一个文件夹下图片过多
java.text.SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String dataPath = sdf.format(new Date());
File dest = new File(realPath + "/" +dataPath + "/" + uuidFileName+suffixName);
// 检测是否存在目录
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
try {
file.transferTo(dest);
} catch (IllegalStateException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//拼接路径
String goodsUrl = "/"+dataPath+"/"+uuidFileName+suffixName;
//存放路径**
goods.setName(goodsUrl);
dser.update(goods);
return "redirect:list";
}
//跳转上传页面
@RequestMapping(“toupload”)
public String toadd(Model model,Goods goods) {
//查询对象
goods = dser.toupdate(goods);
model.addAttribute(“g”, goods);
return “sc”;
}
前台jsp:
<form action="update" method="post" enctype="multipart/form-data">
<table>
<tr>
<td><input type="hidden" name="id" value="${g.id}">上传图片:<input type="file" name="myfile"> </td>
</tr>
<tr>
<td><input type="submit" value="提交"> </td>
</tr>
</table>
</form>