FileManager.java 1.95 KB
Newer Older
张辰's avatar
张辰 committed
1 2 3 4
package com.tanpu.community.manager;

import com.tanpu.common.constant.ErrorCodeConstant;
import com.tanpu.common.exception.BizException;
刘基明's avatar
刘基明 committed
5
import com.tanpu.community.api.beans.resp.FileUploadResp;
张辰's avatar
张辰 committed
6 7
import com.tanpu.community.dao.entity.community.FileRecordEntity;
import com.tanpu.community.service.OSSFileService;
刘基明's avatar
刘基明 committed
8
import com.tanpu.community.util.ConvertUtil;
张辰's avatar
张辰 committed
9 10
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
张辰's avatar
张辰 committed
11
import org.springframework.cache.annotation.Cacheable;
张辰's avatar
张辰 committed
12
import org.springframework.stereotype.Service;
刘基明's avatar
刘基明 committed
13
import org.springframework.util.StringUtils;
张辰's avatar
张辰 committed
14 15 16
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
刘基明's avatar
刘基明 committed
17 18 19
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
张辰's avatar
张辰 committed
20 21 22 23 24 25 26 27

@Slf4j
@Service
public class FileManager {

    @Autowired
    private OSSFileService ossFileService;

刘基明's avatar
刘基明 committed
28
    public FileUploadResp uploadFile(MultipartFile file) {
张辰's avatar
张辰 committed
29 30 31 32 33 34 35 36 37 38 39
        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);
        }

刘基明's avatar
刘基明 committed
40

张辰's avatar
张辰 committed
41
        String originalName = file.getOriginalFilename();
刘基明's avatar
刘基明 committed
42
        if (data.length == 0 || StringUtils.isEmpty(originalName)) {
刘基明's avatar
刘基明 committed
43 44
            throw new BizException("上传文件为空");
        }
刘基明's avatar
刘基明 committed
45 46
        FileRecordEntity fileRecordEntity = ossFileService.uploadFile(data, originalName);
        return ConvertUtil.fileRecordEntity2Resp(fileRecordEntity);
张辰's avatar
张辰 committed
47
    }
刘基明's avatar
刘基明 committed
48

刘基明's avatar
刘基明 committed
49
    public Map<String, String> getFileUrlByIds(List<String> fileIds) {
刘基明's avatar
刘基明 committed
50 51 52
        return ossFileService.queryByIds(fileIds).stream()
                .collect(Collectors.toMap(FileRecordEntity::getFileId, FileRecordEntity::getUrl));
    }
张辰's avatar
张辰 committed
53 54 55 56 57 58

    @Cacheable(value = "local", key = "#id")
    public String getId(String id) {
        System.out.println("cache " + id);
        return "haha " + id;
    }
张辰's avatar
张辰 committed
59
}