十.Springboot实现用户文件的上传

2022-12-27 15:59:13 浏览数 (1)

前言

文件的上传采用的是MultipartFile工具类进行获取的,最后将流保存为临时文件以异步的形式保存到腾讯云cos服务! ps:(本期只贴出关于文件上传块的代码,数据持久层代码将不展示!无外呼增删改查,没啥特别的操作!)

对象存储工具类(cos)

pom依赖引入

代码语言:javascript复制
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <!--腾讯云-->
        <dependency>
            <groupId>com.qcloud</groupId>
            <artifactId>cos_api</artifactId>
            <version>5.6.24</version>
        </dependency>

编写yam文件

代码语言:javascript复制
cos:
  #存储桶访问域名
  baseUrl: https://xxxxxxxxxxxxxxxxxxx.com
  accessKey: AKxxxxxxxxxxxxxxxxxxxpUu4ze4
  secretKey: FF0xxxxxxxxxxxxx90
  #存储桶地区
  regionName: ap-shanghai
  #存储桶名字
  bucketName: oxxxx-xxxxxxx0
  #上传文件前缀路径(eg:/images/)
  folderPrefix: /images

实体类

代码语言:javascript复制
@Data
@Component
// 自动注入yam
@ConfigurationProperties(prefix = "cos")
public class COSConfig {
    private String baseUrl;
    private String accessKey;
    private String secretKey;
    private String regionName;
    private String bucketName;
    private String folderPrefix;
}

工具类

代码语言:javascript复制
public class CosUtils {
    public static COSClient newCosClient(COSConfig cosConfig){
        // 初始化用户身份信息(secretId, secretKey)
        COSCredentials cred = new BasicCOSCredentials(cosConfig.getAccessKey(),cosConfig.getSecretKey());
        // 设置bucket的区域, COS地域的简称请参照 https://www.zijiebao.com/document/product/436/6224
        ClientConfig clientConfig = new ClientConfig(new Region(cosConfig.getRegionName()));
        // 生成cos客户端
        return new COSClient(cred, clientConfig);
    }
}
代码语言:javascript复制
public class FileUtils {
    /**
     * @Description 创建临时文件
     * @Return filepath
     * @Date 2022/10/7 3:13
     */
    public static File transferToFile(MultipartFile multipartFile) throws IOException {
        String originalFilename = multipartFile.getOriginalFilename();
        String prefix = originalFilename.split("\.")[0];
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        File file = File.createTempFile(prefix, suffix);
        multipartFile.transferTo(file);
        return file;
    }
    /**
     * @Description 保留后缀创建新名字,uuid 后缀
     * @Param null
     * @Return {@link null}
     * @Author Ocean_IT
     * @Email 14312400@qq.com
     * @Date 2022/10/7 3:31
     */

    public static String get_new_filename(MultipartFile file){
        String[] strs = file.getOriginalFilename().split("\.");
        String Suffix =strs[strs.length-1];
        String name = IdUtil.simpleUUID() "."  Suffix;
        String folderName = DateUtil.today() "/"  Suffix;
        String key = folderName  "/"  name;
        return key;
    }

}

程序核心逻辑编写

服务层

VideoServiceImpl

代码语言:javascript复制
    /*
     * @Description 上传视频
     * @Param null
     * @Return {@link null}
     * @Author Ocean_IT
     * @Email 14312400@qq.com
     * @Date 2022/10/6 23:32
     */
     @Autowired
    private UploadVideoService uploadVideoService;
    @Autowired
    private CreateRoomDao createRoomDao;
    @Transactional
    public BaseResponse post_video(MultipartFile file, String token) throws Exception {
        String title = file.getOriginalFilename();
        if(title.length()>20){
            title = title.substring(0,15) "...";
        }
        Assert.isTrue(userDao.get_uploadVideo_num(TokenUtils.getOpenid(token)),"你上传视频的已达到上限!");
        Long vid = IdWorker.getId();

        String key = FileUtils.get_new_filename(file);
        File localFile = FileUtils.transferToFile(file);

        Video video = Video.builder().vid(vid).vUrl(cosConfig.getBaseUrl() "/" key).vTitle(title).build();
        Assert.isTrue(videoDao.post_video(video),"出现未知错误,视频保存失败。请联系管理员解决!");
        UploadVideo uploadVideo = UploadVideo.builder().openid(TokenUtils.getOpenid(token)).vid(vid).uvId(IdWorker.getId()).build();
        Assert.isTrue(uploadVideoDao.post_uploadVideo(uploadVideo),"上传记录更新失败,请联系管理员解决!");
        Map<String, Object> map=new HashMap<String,Object>();
        map.put("uploadVideo",uploadVideo);
        map.put("video",video);
        uploadVideoService.UploadToCOS(key,localFile,cosConfig);
        Assert.isTrue(userDao.put_uploadVideo_num(TokenUtils.getOpenid(token),false),"数据库表修改失败,请联系管理员处理!");
        return RespGenerator.success(map);
    }

VideoService

代码语言:javascript复制
    public BaseResponse post_video(MultipartFile file, String token) throws Exception;

UploadVideoServiceImpl 异步执行,需要在启动器添加@EnableAsync

代码语言:javascript复制
@Slf4j
@Service("asyncService")
public class UploadVideoServiceImpl implements UploadVideoService {
    @Async
    public void UploadToCOS(String key, File localPath, COSConfig cosConfig){
        try{
            PutObjectRequest putObjectRequest = new PutObjectRequest(cosConfig.getBucketName(), key, localPath);
            CosUtils.newCosClient(cosConfig).putObject(putObjectRequest);
            log.info("文件上传成功,地址:{}",cosConfig.getBaseUrl() "/" key);
        }catch (Exception e){
            log.error("文件上传cos失败。");
        }finally {
            localPath.delete();
        }
    }
}

UploadVideoService

代码语言:javascript复制
public interface UploadVideoService {
    public void UploadToCOS(String key, File localPath, COSConfig cosConfig);
}

controller控制器

代码语言:javascript复制
    @PostMapping("/video")
    @ApiOperation(value="上传视频",notes = "传入file和token")
    public BaseResponse post_video(MultipartFile file, HttpServletRequest request) throws Exception {
        return videoService.post_video(file,request.getHeader("token"));
    }

0 人点赞