package com.sdut.labex.service.impl;

import com.sdut.labex.service.FileService;
import com.sdut.labex.utils.ResVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.UUID;

/**
 * @author springforest
 * @description 针对表【file(文件)】的数据库操作Service实现
 * @createDate 2023-06-20 13:09:53
 */
@Service
@Slf4j
public class FileServiceImpl implements FileService {

    @Override
    public ResVo uploadFile(MultipartFile file) {
        if (file == null || file.isEmpty()) {
            return ResVo.error("您传了个寂寞");
        }

        // 重命名文件
        String originalFileName = file.getOriginalFilename();
        assert originalFileName != null;
        String ext = "." + originalFileName.split("\\.")[1];
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String fileName = uuid + ext;

        // 指定文件存储路径，相对于项目根目录
        String relativePath = "/src/main/resources/files/";
        String path = System.getProperty("user.dir") + relativePath + fileName;

        System.out.println(path);
        try {
            file.transferTo(new File(path));
        } catch (Exception e) {
            e.printStackTrace();
            return ResVo.error(e.toString());
        }
        return ResVo.ok();
    }
}




