package com.ff.file.service.impl;

import com.ff.base.config.FFConfig;
import com.ff.base.core.domain.AjaxResult;
import com.ff.base.exception.base.BaseException;
import com.ff.base.utils.MessageUtils;
import com.ff.base.utils.file.FileUploadUtils;
import com.ff.base.utils.file.FileUtils;
import com.ff.file.service.ISysFileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * 本地文件存储
 *
 * @author ruoyi
 */
@Service("localSysFileService")
@Slf4j
public class LocalSysFileServiceImpl implements ISysFileService {
    /**
     * 本地文件上传接口
     *
     * @param file 上传的文件
     * @return 访问地址
     * @throws Exception
     */
    @Override
    public AjaxResult uploadFile(MultipartFile file) {
        try {
            // 上传文件路径
            String filePath = FFConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", fileName);
            ajax.put("fileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());
            return ajax;
        } catch (IOException e) {
            log.error("本地文件上传异常,{}", e);
            throw new BaseException(MessageUtils.message("upload.file.exception"), e.getMessage());
        }
    }
}
