Java saves MultipartFile to local directory

1. Required dependencies

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

2. File saving local directory tool class

package com.ruoyi.web.controller.util;

import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.UUID;

public class MultipartFileToFileUtils {
    
    

    /**
     * @param file
     * @param targetDirPath 存储MultipartFile文件的目标文件夹
     * @return 文件的存储的绝对路径
     */
    public static String saveMultipartFile(MultipartFile file, String targetDirPath) {
    
    

        File toFile = null;
        if (file.equals("") || file.getSize() <= 0) {
    
    
            return null;
        } else {
    
    

            /*获取文件原名称*/
            String originalFilename = file.getOriginalFilename();
            /*获取文件格式*/
            String fileFormat = originalFilename.substring(originalFilename.lastIndexOf("."));

            String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");
            toFile = new File(targetDirPath + File.separator + originalFilename);

            String absolutePath = null;
            try {
    
    
                absolutePath = toFile.getCanonicalPath();

                /*判断路径中的文件夹是否存在,如果不存在,先创建文件夹*/
                String dirPath = absolutePath.substring(0, absolutePath.lastIndexOf(File.separator));
                File dir = new File(dirPath);
                if (!dir.exists()) {
    
    
                    dir.mkdirs();
                }

                InputStream ins = file.getInputStream();

                inputStreamToFile(ins, toFile);
                ins.close();

            } catch (IOException e) {
    
    
                e.printStackTrace();
            }
            return absolutePath;
        }

    }

    //获取流文件
    private static void inputStreamToFile(InputStream ins, File file) {
    
    
        try {
    
    
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
    
    
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
    }

    /**
     * 删除本地临时文件
     *
     * @param file
     */
    public static void deleteTempFile(File file) {
    
    
        if (file != null) {
    
    
            File del = new File(file.toURI());
            del.delete();
        }
    }

}

3. Project actual combat

 @ApiOperation("上传文件新版本")
    @PostMapping("/v1/3rd/file/save")
    public ResponseEntity<Object> saveFile(
            @RequestHeader(name = "X-Weboffice-File-Id", defaultValue = "") String fileId,
            @RequestHeader(name = "X-Weboffice-save-type", defaultValue = "auto") String type,
            @RequestHeader(name = "x-wps-weboffice-token", required = false) String token,
            @RequestParam MultipartFile file) {
    
    
        设置初始文件id和版本号
        //cache.put("a2c4d55e28af42a896386d5dcf36", new SoftReference<>(new CacheObject(1, 3600)));
        // TODO 校验token,需要用户根据实际情况实现,此处仅供参考
        if (StringUtils.isNotBlank(token)) {
    
    
            //TODO 需要用户根据实际情况实现
        }

        // TODO 自定义校验规则,需要用户根据实际情况实现,此处仅供参考
        if (StringUtils.isBlank(fileId)) {
    
    
            return new ResponseEntity<>(new OnlineEditingCallbackApiController.ErrorInfo()
                    .setResult(20501001)
                    .setMessage("文件id不能为空"), HttpStatus.BAD_REQUEST);
        }
        String outpath = "";
        String originalFilename = file.getOriginalFilename();
        /*获取文件格式*/
        String fileFormat = originalFilename.substring(originalFilename.lastIndexOf("."));
        JinshanTable jinshanTable = new JinshanTable();
        jinshanTable.setFileId(fileId);
        List<JinshanTable> list = jinshanTableService.selectJinshanTableList(jinshanTable);
        long version = list.get(0).getVersion() + 1;
        if (CollectionUtils.isEmpty(list)) {
    
    
            String path = "D:\\downloadServer\\" + fileId + "\\version1\\";
            outpath = "D:/downloadServer/" + fileId + "/version1/" + originalFilename;
            File file1 = new File(path);
            boolean mkdir = file1.mkdir();
        } else {
    
    
            String path = "D:\\downloadServer\\" + list.get(0).getFileId() + "\\version" + version + "\\";
            outpath = "D:/downloadServer/" + fileId + "/version" + version;
            File file1 = new File(path);
            boolean mkdir = file1.mkdir();
        }
        MultipartFileToFileUtils.saveMultipartFile(file, outpath);

        //保存数据库
        long time = new Date().getTime() / 1000;
        JinshanTable jinshanTable1 = new JinshanTable();
        jinshanTable1.setFileId(fileId);
        jinshanTable1.setVersion(version);
        jinshanTable1.setFileName(originalFilename);
        jinshanTable1.setCreateTime(time);
        jinshanTable1.setCreator("idc" + fileId);
        jinshanTable1.setDownloadUrl("http://xxxx:8100/" + fileId + "/version" + version + "/" + file.getOriginalFilename() + fileFormat);
        jinshanTable1.setSize(file.getSize());
        jinshanTable1.setPreviewPages(list.get(0).getPreviewPages());
        jinshanTable1.setModifier("idm" + fileId);
        jinshanTable1.setMofifyTime(time);
        jinshanTableService.insertJinshanTable(jinshanTable1);

        // TODO 组装文件信息,需要用户根据实际情况实现,此处仅供参考
        FileInfoBuilderSave fileInfo = new FileInfoBuilderSave()
                .setFile(new FileInfoBuilderSave.FileInfo()
                        .setId(fileId)
                        .setName(originalFilename)
                        .setVersion(Math.toIntExact(list.get(0).getVersion() + 1))
                        .setSize(Math.toIntExact(file.getSize()))
                        .setDownloadUrl("http://xxxx:8100/" + fileId + "/version" + version + "/" + file.getOriginalFilename())
                );

        logger.info("param = {}", "上传文件新版本");
        return new ResponseEntity<>(fileInfo, HttpStatus.OK);
    }

4. Results

insert image description here
insert image description here
insert image description here
At this point, file storage and version management services are completed.

Guess you like

Origin blog.csdn.net/zouyang920/article/details/130972854