Spring boot上传图片

本文详细介绍了使用SpringBoot实现图片上传的方法,包括如何通过MultipartFile获取文件,动态创建目录,处理文件上传异常,并将文件路径保存到Goods实体中。同时提供了controller层代码示例和前端jsp页面代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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>
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值