FileManager.java 1.54 KB
package com.tanpu.community.manager;

import com.tanpu.common.constant.ErrorCodeConstant;
import com.tanpu.common.exception.BizException;
import com.tanpu.community.dao.entity.community.FileRecordEntity;
import com.tanpu.community.service.OSSFileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class FileManager {

    @Autowired
    private OSSFileService ossFileService;

    public FileRecordEntity uploadFile(MultipartFile file) {
        if (file == null) {
            throw new BizException(ErrorCodeConstant.FILE_UPLOAD_FAIL);
        }

        byte[] data = null;
        try {
            data = file.getBytes();
        } catch (IOException e) {
            throw new BizException(ErrorCodeConstant.FILE_UPLOAD_FAIL);
        }


        String originalName = file.getOriginalFilename();
        if (data.length==0 || StringUtils.isEmpty(originalName)){
            throw new BizException("上传文件为空");
        }
        return ossFileService.uploadFile(data, originalName);
    }

    public Map<String,String> getFileUrlByIds(List<String> fileIds){
        return ossFileService.queryByIds(fileIds).stream()
                .collect(Collectors.toMap(FileRecordEntity::getFileId, FileRecordEntity::getUrl));
    }
}