mongo文件服务器简单实现

1. 文件服务器需求

本文件服务器用于小型文件的存储,如用户为记录添加的图片、pdf说明。

2. 文件服务器组件

  • mongodb:采用mongobd进行文档存储,mongodb支持多种数据格式,将文档转化为二进制文件保存
  • springboot:快速构建独立运行java项目
  • swagger-ui:快速生成接口文档,便于测试

3. 图片上传实现

  • Entity层
@Data
@NoArgsConstructor
@Document(collection = "images")
public class Image {
    @Id
    String _id;
    private String name;
    private String contentType;
    private long size;
    private byte[] content;
}
  • Repository层
public interface IImageRepository extends MongoRepository<Image,String>{
}
  • Service层
@Service
public class ImageServiceImpl implements IImageService {

    @Autowired
    private IImageRepository imageRepository;

    @Value("${fileServer.host}")
    private String serverhost;

    @Override
    public String uploadImage(MultipartFile file) throws FileServerException {
        if (!file.isEmpty()) {
            try {
                //源文件名
                String fileName = file.getOriginalFilename();
                //源文件后缀
                String fileSuffix = fileName.substring(fileName.lastIndexOf("."));
                //数据库文件Id,且以id为新的文件名
                String fileId = UUID.randomUUID() + "";

                if (file.getSize() > 1000 * 1024) {
                    throw new FileServerException("上传失败,图片大于1MB");
                }
                if (!(fileSuffix.equals(".jpg") || fileSuffix.equals(".jpeg") || fileSuffix.equals(".png"))) {
                    throw new FileServerException("上传失败,不支持该图片格式");
                }
                Image image = new Image();
                image.setName(fileId);
                image.setSize(file.getSize());
                image.setContentType(file.getContentType());
                image.setContent(file.getBytes());
                Image newImage = imageRepository.save(image);
                return ResultBuilder.getResult(true, serverhost + "/image/" + newImage.get_id(), "图片上传成功", "");
            } catch (Exception e) {
                throw new FileServerException("上传失败," + e.getMessage());
            }
        } else {
            throw new FileServerException("文件不存在");
        }
    }
  • Controller层
@Api(value = "ImageController", description = "图片上传与查看接口")
@RestController
@RequestMapping(value = "/image")
public class ImageController {

    @Autowired
    private IImageService imageService;

    @ApiOperation(value = "上传图片", notes = "添加图片")
    @PostMapping(value = "/uploadImage")
    public String uploadImage(@ApiParam(value = "上传的图片", required = true) @RequestParam("file") MultipartFile file) throws FileServerException {
        return imageService.uploadImage(file);
    }

    @ApiOperation(value = "在线查看图片", notes = "查看图片")
    @ApiImplicitParam(name = "imageId", value = "图片id", required = true, paramType = "path", dataType = "String")
    @GetMapping(value = "/{imageId}")
    @ResponseBody
    public ResponseEntity getImageById(@PathVariable String imageId) throws FileServerException {
        Image image = imageService.getImageById(imageId);
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "fileName=\"" + image.getName() + "\"")
                .header(HttpHeaders.CONTENT_TYPE, image.getContentType())
                .header(HttpHeaders.CONTENT_LENGTH, image.getSize() + "")
                .header("Connection", "close")
                .body(image.getContent());

    }
}
 
  

-效果展现
上传图片接口
mongo文件服务器简单实现_第1张图片
在线查看接口
mongo文件服务器简单实现_第2张图片

4. 文件大小限制处理

springboot上传文件默认限制为1MB,需要依据实际情况进行调整,在配置文件中修改属性值。

spring.http.multipart.max-file-size=15MB
spring.http.multipart.max-request-size=20MB

参考文章:https://waylau.com/mogodb-file-server-with-spring-boot

你可能感兴趣的:(springboot)