FileServiceImpl.java 1.5 KB
package com.wondertek.service.impl;

import com.wondertek.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @Description:
 * @Author W5669
 * @Create 2025/7/24
 * @Version 1.0
 */
@Service
@Slf4j
public class FileServiceImpl implements FileService {
    @Override
    public void upload(MultipartFile backupFile, String filePath) throws IOException {
        // 检查文件是否为空
        if (backupFile.isEmpty()) {
            throw new IllegalArgumentException("上传文件为空");
        }

        // 创建目标文件对象
        File dest = new File(filePath);

        // 检查目标目录是否存在,不存在则创建
        File parentDir = dest.getParentFile();
        if (!parentDir.exists()) {
            if (!parentDir.mkdirs()) {
                throw new IOException("目录创建失败: " + parentDir.getAbsolutePath());
            }
        }

        try {
            // 转存文件到指定路径
            backupFile.transferTo(dest);
        } catch (IOException e) {
            throw new IOException("文件写入失败: " + e.getMessage(), e);
        } catch (IllegalStateException e) {
            throw new IOException("文件状态错误: " + e.getMessage(), e);
        }


    }
}