SpringBoot realizes uploading files

SpringBoot realizes uploading files

1. Front-end upload files use apiPost to simulate file upload operations.
The use of apiPost:
insert image description here
2. Write the SpringBoot back-end interface, complete the file reception, and save it to the server.

/**
     * 注意这里的文件名要与前端传递过来的一致,否则报错。
     * @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;
    }

The file upload operation is finally completed.

Guess you like

Origin blog.csdn.net/m0_44980168/article/details/130112453