Vue3+SpringBoot实现文件上传详细教程
作者:mmseoamin日期:2024-04-27

      文件上传的功能实现是我们做Web应用时候最为常见的应用场景,比如:实现头像的上传,Excel文件数据的导入等功能,都需要我们先实现文件的上传,然后再做图片的裁剪,excel数据的解析入库等后续操作。

    今天通过这篇文章,我们就来一起学习一下如何在Vue3+SpringBoot中实现文件的上传,这篇文章主要使用图片上传进行讲解。

    主要逻辑为:本案例实现商品信息的上传功能,包含商品的文字信息及商品图片

如下图显示:

Vue3+SpringBoot实现文件上传详细教程,第1张

点击“新增”

Vue3+SpringBoot实现文件上传详细教程,第2张

具体核心代码,如下

1. SpringBoot 中核心代码

@RestController
@RequestMapping("/bg/product")
public class ProductController {
    @Autowired
    private ProductService productService;
    @RequestMapping("/queryall")
    private Message queryAll(){
        return productService.queryall();
    }
    @RequestMapping("/save")
    private Message addProduct(@RequestBody Product product){
        return productService.save(product);
    }
    @RequestMapping("/upload")
    private String ImageUpload(@RequestParam MultipartFile file, HttpServletRequest request)throws Exception{
        // 综合考虑:两个位置都上传文件
        //2. 指定文件上传的目录(target/classes/xxx)
        //2.1 文件存储到此位置,可以提供页面的访问(当前target中的内容不会打包上传到服务器上)
        String path_target = ClassUtils.getDefaultClassLoader().getResource("static").getPath()+"/upload/";
        //2. 指定文件上传的目录(当前项目的src/main/resources/static/upload 下)
        //2.1 文件存储到此位置,可以保存上传的图片,并打包上传到服务器上(在项目中执行 install 就可以生成target中的所有内容)
        String path = System.getProperty("user.dir")+"/src/main/resources/static/upload";
        //3. 判断此目录是否存在
        File fileDir_target = new File(path_target);
        if(!fileDir_target.exists()){
            fileDir_target.mkdirs();
        }
        File fileDir = new File(path);
        if(!fileDir.exists()){
            fileDir.mkdirs();
        }
        //4. 生成新的名字
        String oldName = file.getOriginalFilename();
        String newName = UUID.randomUUID().toString().replaceAll("-","")+oldName.substring(oldName.lastIndexOf("."),oldName.length());
        //5. 指定生成的文件
        File file_target = new File(fileDir_target.getAbsolutePath()+File.separator+newName);
        File file_1 = new File(fileDir.getAbsolutePath()+File.separator+newName);
        //6. 文件的生成
        file.transferTo(file_1);
        FileCopyUtils.copy(file_1,file_target);
        //7. 生成http的访问路径
         String httpPath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+"/"
                + request.getContextPath()+"upload/"+newName;
        System.out.println("path:"+path);
        System.out.println("path_target:"+path_target);
        System.out.println("httpPath:"+httpPath);
        return httpPath;
    }
}

2. vue中核心代码

    流程为:先将图片上传到Springboot服务器上,服务器返回给图片的http访问地址,将http访问地址与商品的信息再一起上传到服务器上


到此,此案例整理完毕!