开发环境及工具:

java 环境 :JDK 1.8

Maven环境: Maven 3.6.3

MongoDB : 数据库

开发工具:

IDEA 2020.3.2

Postman

Spring Boot 连接 MongoDB 相关配置:

https://blog.csdn.net/LZW15082682930/article/details/114678505

方法一   

承接上文,有关MongoDB配置转到  https://blog.csdn.net/LZW15082682930/article/details/114678505

向MongoDB中写入图片(视频方法与此类似)。

注 :  上传的文件默认最大 10MB,超过文件大小会报错。

在application.yml中配置:

spring:
  #上传大小限制
  servlet:
    multipart:
      max-file-size: 50MB
      max-request-size: 50MB

图片上传

第一步  编写实体类

Photos.java

@Document(collection = "photos")
public class Photos {
    @Id
    private String id;      // 文件 id
    private String pname;   // 文件名
    private String contentType; // 文件类型
    private Binary content;     // 文件内容
    private long size;  // 文件大小
    private String createTime;    //上传时间
//    private String uname;       // 上传者的用户名

其中 setter() 、getter() 、toString()方法省略

第二步  编写Service层

PhotosInfoService接口

public interface PhotosInfoService{

    boolean insert(Photos photos);

}

实现类: PhotosInfoServiceImpl.java

其中  MongoTemplate 不是自己编写的,导入即可

 import org.springframework.data.mongodb.core.*

或者根据自己需要导入:

import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

@Service
public class PhotosInfoServiceImpl implements PhotosInfoService {
    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    public boolean insert(Photos photos) {
        Photos result = mongoTemplate.save(photos);
        if (result == null) {
            return false;
        }
        return true;
    }

}

第三步  编写Controller

上传图片并写入数据库


@RestController
@RequestMapping("photos")
public class PhotosController {
    @Autowired
    PhotosInfoService photosInfoService;

    /**
     * 上传图片并写入MongoDB
     *
     * @param multipartFile
     * @return
     */
    @PostMapping("upload")
    @ResponseBody
    public Result uploadImage(@RequestParam(value = "image") MultipartFile multipartFile) {
        if (multipartFile.isEmpty()) {
            return Result.sendFailMsg("上传的图片为空,请重试...");
        }
        try {
            String pname = multipartFile.getOriginalFilename();
            Photos photos = new Photos();
            photos.setId(UserUtils.createId());
            photos.setPname(pname);     // 文件名
            photos.setContent(new Binary(multipartFile.getBytes()));    // 文件内容
            photos.setContentType(multipartFile.getContentType());  // 文件类型
            photos.setSize(multipartFile.getSize());    // 文件大小
            photos.setCreateTime(UserUtils.create_time());   // 创建时间
            // 写入到本地文件夹下
//            multipartFile.transferTo(new File(Common.FilePath + multipartFile.getOriginalFilename()));
            // 将图片信息以二进制流的形式写入数据库中
            boolean isSuccess = photosInfoService.insert(photos);
            if (isSuccess) {
                return Result.sendSuccessMsg("图片上传成功...");
            } else {
                return Result.sendFailMsg("图片上传失败,请重试...");
            }
        } catch (IOException e) {
            e.printStackTrace();
            return Result.sendFailMsg("图片上传失败,请重试");
        }
    }

  

   
}

其中 创建ID的函数如下:

   /**
     * 随机创建Uid
     *
     * @return
     */
    public static String createId() {
        String Uid;
        String result = "";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String date = simpleDateFormat.format(new Date());
        Random random = new Random();
        for (int i = 0; i < 5; i++) {
            result += random.nextInt(10);
        }
        Uid = date + result;
        return Uid;
    }

创建时间函数如下:

    public static String create_time(){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = simpleDateFormat.format(new Date());
        return date;
    }

Result 类用于返回数据,可以根据自己需要编写返回String或者直接不返回数据。


第四步  查看写入的图片

MongoDB数据查询:

//查询数据
db.photos.find()

二进制文件

图片下载

下载图片并写入到本地磁盘

第一步  编写Service

PhotossService.interface

public interface PhotosInfoService{

    boolean insert(Photos photos);
    //根据 id 查询图片信息
    Photos queryPhotosById(String id);

}

 

第二步  编写实现类


@Service
public class PhotosInfoServiceImpl implements PhotosInfoService {
    @Autowired
    MongoTemplate mongoTemplate;
   
     /**
     * 根据 id 查询
     * @param id
     */
    @Override
    public Photos queryPhotosById(String id) {
        Query query = new Query(Criteria.where("id").is(id));
        List<Photos> list = mongoTemplate.find(query,Photos.class);
        Photos result = null;
        for (Photos photos : list){
            result = photos;
        }
        return result;

    }
}

 

第三步  编写Controller

我这里以id查询为例:

@RestController
@RequestMapping("photos")
public class PhotosController {
    @Autowired
    PhotosInfoService photosInfoService;
    

    /**
     * 将返回的结果写到本地磁盘
     *
     * @param id
     * @return
     */
    @RequestMapping("download")
    public Result downloadImages(String id) {
        try {
            Photos photos = photosInfoService.queryPhotosById(id);
            byte[] bytes;
            bytes = photos.getContent().getData();
            File file = new File(Common.FilePath + photos.getPname());
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            fileOutputStream.write(bytes);
            fileOutputStream.flush();
            fileOutputStream.close();
            return Result.sendSuccessMsg("下载成功...");
        } catch (IOException e) {
            e.printStackTrace();
            return Result.sendFailMsg("下载失败,请重试...");
        }

    }
}

 

其中   

File file = new File(Common.FilePath + photos.getPname());

File()中换成自己的输出路径。

代码编写完成后,启动程序。

第四步  Postman发起请求

 

输出的文件:

以上就是MongoDB 图片的上传与下载,视频上传与下载与之类似。

 

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐