当我们直接用表单将数据传送到后台的时候,需要在表单标签加上enctype="multipart/form-data"语句。具体实现如下:
html代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="http://localhost:8080/SSS/authentication/uploadImg" method="post" enctype="multipart/form-data">
<input type="text" name="userId"/>
<input type="file" name="img"/>
<input type="submit" name="提交"/>
</form>
</body>
</html>
Java代码:
@ResponseBody
@RequestMapping("/uploadImg")
public void uploadImg(MultipartFile img,HttpServletRequest request) throws IOException{
//获取图片的完整名称
String imgFile = img.getOriginalFilename();
//使用随机生成的字符串+图片的文件扩展名作为图片存储的名称
String newFileName = UUID.randomUUID().toString() + imgFile.substring(imgFile.lastIndexOf("."));
//将图片保存在硬盘
img.transferTo(new File("F:\\"+newFileName));
//将图片保存到数据库
UserInfo user=userInfoService.getuserById(Long.parseLong(request.getParameter("userId")));
user.setCardUrl(newFileName);
}
这样就实现了图片保存到指定路径,以及将图片的路径保存到数据库的功能。