欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SpringBoot2.x集成MongonDB gridFs实现文件的上传下载

程序员文章站 2022-05-01 08:10:14
...

新建配置类mongondbConfig

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSBuckets;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MongoConfig {
    @Value("${spring.data.mongodb.database}")
    String db;

    @Bean
    public GridFSBucket getGridFSBucket(MongoClient mongoClient) {
        MongoDatabase database = mongoClient.getDatabase(db);
        GridFSBucket bucket = GridFSBuckets.create(database);
        return bucket;
    }
}

文件上传

@Override
	public ResultBean<File> createFile(MultipartFile multipartFile,String applyId,String userId) {		
		File file = File.builder().build();
        ResultBean.ResultBeanBuilder<File> resultBeanBuilder = ResultBean.builder();
        try {
            Date createTime = new Date();
            String originalFilename = multipartFile.getOriginalFilename();
            String name = originalFilename.substring(0,originalFilename.lastIndexOf("."));
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));        
            String ContentType = multipartFile.getContentType();        
            String gridFsId = "";
            ObjectId gridFSFile1 = gridFsTemplate.store(multipartFile.getInputStream(), originalFilename, ContentType);
            gridFsId = gridFSFile1.toString();                 
            file = File.builder().originalFilename(multipartFile.getOriginalFilename()).fileName(name).extension(extension)
            		.size(multipartFile.getSize()).gridFsId(gridFsId).createTime(createTime).ownerId(userId).appId(applyId)
            		.status("1").isEncryption("2").modifiedTime(createTime).deleteFlag("0").build();
        } catch (IOException e) {
            e.printStackTrace();
            return resultBeanBuilder.state(new ResultBeanState(FileEnum.CREATE_ERROR)).data(file).describe(e.getMessage()).build();
        }
        return resultBeanBuilder.state(new ResultBeanState(FileEnum.CREATE_SUCCESS)).data(fileRepository.save(file)).build();
    
	}

文件下载

@Override
	public ResultBean<File> readByGridFsId(String gridFsId) {		
		ResultBean.ResultBeanBuilder<File> resultBeanBuilder = ResultBean.builder();
		File file = fileRepository.findByGridFsIdAndDeleteFlag(gridFsId,"0");
		GridFSFile gridFSFile = gridFsDao.find(gridFsId);
		MongoDatabase db = mongoTemplate.getDb();		
        try {                         
            // 获取原文件名
            String fileName = new String(gridFSFile.getFilename().getBytes("UTF-8"), "ISO8859-1");            
            if (httpServletRequest.getHeader("User-Agent").toUpperCase().indexOf("MSIE") < 0){ 
                httpServletResponse.setHeader("Content-Disposition", "attachment; filename="+  new String(gridFSFile.getFilename().getBytes("GBK"), "ISO8859-1"));
            } else{
                httpServletResponse.setHeader("Content-Disposition", "attachment; filename="+ URLEncoder.encode(fileName, "UTF-8"));//IE浏览器
            }
            // 设置下载文件名,解决乱码
            httpServletResponse.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); 
            httpServletResponse.setContentType("application/octet-stream");            
            OutputStream outputStream = httpServletResponse.getOutputStream();
            GridFSBuckets.create(db).downloadToStream(gridFSFile.getObjectId(),outputStream);
            outputStream.flush();
            outputStream.close();                    
        } catch (IOException e) {
            return resultBeanBuilder.state(new ResultBeanState(FileEnum.READ_ERROR)).data(file).describe(e.getMessage()).build();
        }
        return resultBeanBuilder.state(new ResultBeanState(FileEnum.READ_SUCCESS)).data(file).build();
    }