表单提交之上传图片

来源:互联网 发布:美工自学多久能自己做 编辑:程序博客网 时间:2024/05/22 12:53

当我们直接用表单将数据传送到后台的时候,需要在表单标签加上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);}

这样就实现了图片保存到指定路径,以及将图片的路径保存到数据库的功能。

原创粉丝点击