springMVC接收表单传来的file,并上传

本文介绍了一个基于Java的文件上传功能实现方法,包括Controller层的请求处理及Service层的具体业务逻辑。通过MultipartFile进行文件接收,并利用try-catch块确保文件能够正确地保存到指定目录下。

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

controller层

@RequestMapping(value = "/fileupload.do")

@ResponseBody
public JsonResult<Boolean> fileupload(@RequestParam(value = "imgUpload") MultipartFile uploadFile, HttpServletRequest request)  {
String contextPath = request.getSession().getServletContext().getRealPath("/document");
Boolean b = false;
try{
b = fileService.saveFile(uploadFile,contextPath);
}catch(Exception e){
return new JsonResult<Boolean>(e.getMessage());
}
return new JsonResult<Boolean>(b);

}

service层

@Transactional

public Boolean saveFile(MultipartFile uploadFile, String contextPath) {
String filename = uploadFile.getOriginalFilename();
String fpath = contextPath;
File file = new File(fpath+File.separator+filename);
try {
uploadFile.transferTo(file);//上传文件
} catch (IllegalStateException e) {
e.printStackTrace();
throw new IllegalStateException("保存失败");
} catch (IOException e) {
e.printStackTrace();
throw new IllegalStateException("保存失败");
}
fileDao.saveFile(filename,fpath);//保存文件路径
return true;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值