当前位置:   article > 正文

springboot上传文件的两种方式_vue+spring boot上传视频转二进制流

vue+spring boot上传视频转二进制流
1.文件保存在服务器,url地址保存在数据库
	/**
	 * 1.文件保存在服务器,url地址保存在数据库
     * 上传成功之后返回成功保存的url地址
     */
@PostMapping("/upload")
    public @ResponseBody String upload(@RequestParam MultipartFile file, HttpServletRequest request){
        if(!file.isEmpty()){
            String uploadPath = "C:\uploadFile";
            // 如果目录不存在则创建
            File uploadDir = new File(uploadPath);
            if (!uploadDir.exists()) {
                uploadDir.mkdir();
            }
            String OriginalFilename = file.getOriginalFilename();//获取原文件名
            String suffixName = OriginalFilename.substring(OriginalFilename.lastIndexOf("."));//获取文件后缀名
            //重新随机生成名字
            String filename = UUID.randomUUID().toString() +suffixName;
            File localFile = new File(uploadPath+"\"+filename);
            try {
                file.transferTo(localFile); //把上传的文件保存至本地
                /**
                 * 这里应该把filename保存到数据库,供前端访问时使用
                 */
                return filename;//上传成功,返回保存的文件地址
            }catch (IOException e){
                e.printStackTrace();
                System.out.println("上传失败");
                return "";
            }
        }else{
            System.out.println("文件为空");
            return "";
        }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
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();
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
3.前端代码
<form action="/upload" method="post" enctype="multipart/form-data">
    <input type="file" name="file" /><br/>
    <input type="submit" name="" id="" value="提交" />
</form>
  • 1
  • 2
  • 3
  • 4
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/384022
推荐阅读
相关标签
  

闽ICP备14008679号