GridFS上传和下载模板

GridFS上传和下载模板 

import com.lxw.manage_cms.ManageCmsApplication;
import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSDownloadStream;
import com.mongodb.client.gridfs.model.GridFSFile;
import org.bson.types.ObjectId;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsResource;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@SpringBootTest(classes = ManageCmsApplication.class)
@RunWith(SpringRunner.class)
public class GridFSTest {

    @Autowired
    private GridFsTemplate gridFsTemplate;
    @Autowired
    private GridFSBucket gridFSBucket;//配置类中的"桶"

    //上传模板
    @Test
    public void testUploadFile() throws FileNotFoundException {
        String path = this.getClass().getResource("/templates/").getPath();//获取模板文件所在的目录
        File file = new File(path + "index_banner.html");
        //2 输入字节流 InputStream是抽象类
        InputStream inputStream = new FileInputStream(file);//file是要读取的文件路径
        //1 上传GridFS
        ObjectId objectId = gridFsTemplate.store(inputStream, "ss_index_banner.html");//指定上传后的文件名
        System.out.println(objectId);
    }


    //下载模板
    @Test
    public void testDownloadFile() throws IOException {
        //查询要下载的文件
        GridFSFile file = gridFsTemplate.findOne(
                Query.query(Criteria.where("_id").is("6501f4ff22bd126780199bde")));
        //通过GridFSBucket打开下载流
        GridFSDownloadStream gridFSDownloadStream = gridFSBucket.openDownloadStream(file.getObjectId());
        //创建操作流的gritFS对象
        GridFsResource gridFsResource = new GridFsResource(file, gridFSDownloadStream);

        //下载
        /**
         * 使用 Java 8 中的 Stream API 将 InputStream 转换为字符串。
         * InputStreamReader 读取输入流,BufferedReader().lines() 帮助我们将这个 InputStream 转换为一个 String 的流。
         * 我们可以看到,Collectors.join() 被用来连接流中的所有字符串,然后返回一个单一的字符串。
         */
        InputStream inputStream = gridFsResource.getInputStream();//获取输入字节流对象
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream);//InputStreamReader 读取输入流
        Stream streamOfString = new BufferedReader(inputStreamReader).lines();//将inputStream转换为String流
        String streamToString = streamOfString.collect(Collectors.joining());//连接流中的所有字符串
        System.out.println(streamToString);


    }

}

你可能感兴趣的:(项目,GridFS)