SpringBoot实现上传文件

SpringBoot实现上传文件

1.前端上传文件用apiPost模拟文件上传操作。
apiPost的使用:
在这里插入图片描述
2.写SpringBoot后端接口,完成文件的接收,并保存到服务器中。

/**
     * 注意这里的文件名要与前端传递过来的一致,否则报错。
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping("/upload2")
    public String upload(@RequestParam("file") MultipartFile file) throws Exception {
    
    
        String name="file2";
        Map<String,Object> map=new HashMap();
//        获取文件名
        String name1 = file.getName();
//        获取文件大小
        long size = file.getSize();
//        获取文件类型
        String contentType = file.getContentType();
//        放到map中
        map.put("name",name1);
        map.put("size",size);
        map.put("type",contentType);
//        遍历map集合
        System.out.println(map.toString());

        // 设置上传至项目文件夹下的uploadFile文件夹中,没有文件夹则创建
//        dir.exists():判断路径是否存在。
//        dir.mkdirs():如过不存在,创建文件夹
        File dir = new File("src/main/resources/file");
        if (!dir.exists()) {
    
    
            dir.mkdirs();
        }

//        再创建一个File对象,用来做最总的存储。
//        getAbsolutePath():获取绝对的路径的。
//        File.separator 的作用相当于 ' \  ',因为在不同的操作系统中,他的分隔符是不一样的,因此我们需要动态变化。
        File file1 = new File(dir.getAbsolutePath() + File.separator + name + ".txt");
//        通过transferTo()对前端传递过来的文件进行存储。
        file.transferTo(file1);
        return "上传完成!文件名:" + name;
    }

最终完成文件的上传操作。

猜你喜欢

转载自blog.csdn.net/m0_44980168/article/details/130112453