1、在nacos中配置minio参数
2、controller层
package com.heima.wemedia.controller.v1;import com.heima.model.common.dtos.ResponseResult;
import com.heima.wemedia.service.WmMaterialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;@RestController
@RequestMapping("/api/v1/material")
public class WmMaterialController {@AutowiredWmMaterialService wmMaterialService;@PostMapping("/upload_picture")public ResponseResult upload(MultipartFile multipartFile){return wmMaterialService.upload(multipartFile);}}
3、接口实现类
封装minio上传工具Minio: 封装MinIO为starter_moreCalm的博客-CSDN博客
获取用户id的前置工作 微服务:从header中获取用户存入当前线程_moreCalm的博客-CSDN博客
package com.heima.wemedia.service.impl;import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.wemedia.model.po.WmMaterial;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;import java.io.IOException;
import java.time.LocalDateTime;
import java.util.UUID;/*** <p>* 自媒体图文素材信息表 服务实现类* </p>** @author itcast* @since 2023-08-05*/
@Service
@Slf4j
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {@Autowiredprivate FileStorageService fileStorageService;/*图片上传*/@Overridepublic ResponseResult upload(MultipartFile file) {/*参数校验*/if(file == null || file.getSize() <= 0){return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);}/*上传图片到minio*///生成uuidString fileName = UUID.randomUUID().toString().replace("-", "");//获取图片名称String originalFilename = file.getOriginalFilename();//获取文件扩展名(后缀名)String postfix = originalFilename.substring(originalFilename.lastIndexOf("."));//定义文件id用来接收上传的图片String fileId = null;try {fileId = fileStorageService.uploadImgFile("", fileName + postfix, file.getInputStream());log.info("上传图片到MinIO中,fileId:{}",fileId);} catch (IOException e) {e.printStackTrace();log.error("WmMaterialServiceImpl-上传文件失败");}/*保存数据到数据库中*/WmMaterial wmMaterial = new WmMaterial();wmMaterial.setUserId(WmThreadLocalUtil.getUser().getId());//用户idwmMaterial.setUrl(fileId);//图片地址wmMaterial.setType(0);//文件类型(0 图片 1 视频)wmMaterial.setCollection(0);//是否收藏wmMaterial.setCreatedTime(LocalDateTime.now());//创建时间save(wmMaterial);//保存数据库/*返回结果*/return ResponseResult.okResult(wmMaterial);}
}