springboot上传文件的两种方式
1.文件保存在服务器,url地址保存在数据库
2.直接把文件以二进制形式保存到数据库中数据类型为blob的一个字段
/**
*上传图片,使用mybatis-plus保存到数据库
*User为实体类,数据库对应user表,有id、image两个属性
*/
@PostMapping("/upload")
@ResponseBody
public String upload(@RequestParam("file") MultipartFile file) throws Exception{
if(!file.isEmpty()){
User user=new User();
user.setImage(file.getBytes());
userMapper.insert(user);
}
return "ok";
}
/**
*前端通过id获取数据库中的图片
*/
@GetMapping("/getImage")
@ResponseBody
public void getImage(String id,HttpServletResponse resp) throws Exception{
User user=userMapper.selectById(id);
byte[] image = (byte[])user.getImage();
resp.setContentType("image/jpeg");
ServletOutputStream out = resp.getOutputStream();
out.write(image);
out.flush();
out.close();
}
3.前端代码
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" /><br/>
<input type="submit" name="" id="" value="提交" />
</form>
上一篇:
通过多线程提高代码的执行效率例子
