1、上传:

private static Logger log = LoggerFactory.getLogger(MongoDbFSUtil.class);

   private static final class MongoInstance {
public final static MongoClient client;
static {
client = new MongoClient("localhost", 27017);
}
} public static MongoDatabase getDatabase(String databaseName) {
return MongoInstance.client.getDatabase(databaseName);
} /**
* 上传文件
* @param file
* @param databaseName
* @return
*/
public static String uploadFileToGridFS(File file,String databaseName) {
InputStream in = null;
String returnId = null;
String pathName = file.getPath();
String[] pathNameArray = pathName.split("\\\\");
String[] name = pathNameArray[pathNameArray.length-1].split("\\.");
String filename = name[0];
String type = name[name.length-1];
try {
in = new FileInputStream(file);
GridFSBucket bucket = GridFSBuckets.create(getDatabase(databaseName));
GridFSUploadOptions options = new GridFSUploadOptions();
//设置除filename以为的其他信息
Document metadata = new Document();
metadata.append("contentType", type);
options.metadata(metadata);
// ObjectId fileId = bucket.uploadFromStream(filename+type, in,options);
ObjectId fileId = bucket.uploadFromStream("123456", in,options);
returnId = fileId.toHexString();
log.info("文件上传成功");
} catch (IOException e) {
log.info("upload fail:" + e);
} finally {
try {
in.close();
} catch (IOException e) {
log.info("close inputstream fail:" + e);
}
}
return returnId;
}
另外一种上传:使用
  1. @Autowired
  2.  
    private GridFsTemplate gridFsTemplate;

UserAO user = (UserAO) SecurityUtils.getSubject().getPrincipal();
Part part = request.getPart("file");
// 获得提交的文件名
String fileName = part.getSubmittedFileName();
// 获得文件输入流
InputStream ins = part.getInputStream();
// 获得文件类型
String contentType = part.getContentType();
// 将文件存储到mongodb中,mongodb 将会返回这个文件的具体信息
GridFSFile gridFSFile = gridFsTemplate.store(ins, fileName, contentType);
FileInfoAO fileInfo = new FileInfoAO();
fileInfo.setContentType(contentType);
fileInfo.setFileName(fileName);
fileInfo.setLastUpdateBy(user != null ? user.getId() : null);
fileInfo.setMongoFileId(gridFSFile.getId().toString());
return ServiceResultHelper.genResultWithSuccess(fileInfo);

2、下载
@RequestMapping("/downLoadFile")
public void downLoadFile(String fileId, HttpServletRequest request, HttpServletResponse response)throws Exception{
Query query = Query.query(Criteria.where("filename").is("123456"));
// 查询单个文件
GridFSDBFile gfsfile = gridFsTemplate.findOne(query);
if (gfsfile == null) {
return;
}
String fileName = gfsfile.getFilename().replace(",", "");
//处理中文文件名乱码
if (request.getHeader("User-Agent").toUpperCase().contains("MSIE") ||
request.getHeader("User-Agent").toUpperCase().contains("TRIDENT")
|| request.getHeader("User-Agent").toUpperCase().contains("EDGE")) {
fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
} else {
//非IE浏览器的处理:
fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
}
// 通知浏览器进行文件下载
response.setContentType(gfsfile.getContentType());
response.setHeader("Content-Disposition", "attachment;filename=\"" + "222.png" + "\"");
gfsfile.writeTo(response.getOutputStream()); }

springboot实现mongodb上传下载的更多相关文章

  1. SpringBoot图文教程4—SpringBoot 实现文件上传下载

    有天上飞的概念,就要有落地的实现 概念+代码实现是本文的特点,教程将涵盖完整的图文教程,代码案例 文章结尾配套自测面试题,学完技术自我测试更扎实 概念十遍不如代码一遍,朋友,希望你把文中所有的代码案例 ...

  2. SpringBoot的文件上传&下载

    前言:不多BB直接上代码 文件上传 pom依赖添加commons-io <!-- 上传/下载jar https://mvnrepository.com/artifact/commons-io/c ...

  3. spring-boot 实现文件上传下载

    @Controller public class FileUploadCtrl { @Value("${file.upload.dir}") private String path ...

  4. springboot文件上传下载简单使用

    springboot的文件上传比较简单 一.使用默认的Resolver:StandardServletMultipartResolver controller package com.mydemo.w ...

  5. SpringBoot下文件上传与下载的实现

    原文:http://blog.csdn.net/colton_null/article/details/76696674 SpringBoot后台如何实现文件上传下载? 最近做的一个项目涉及到文件上传 ...

  6. springboot整合vue实现上传下载文件

    https://blog.csdn.net/yhhyhhyhhyhh/article/details/89888953 文章目录 springboot整合vue实现上传下载文件 1上传下载文件api文 ...

  7. springboot简易上传下载

    1.导入上传下载依赖: <dependency> <groupId>commons-fileupload</groupId> <artifactId>c ...

  8. 仵航说 前后端分离,文件上传下载(springBoot+vue+elementUI)仵老大

    1.介绍 ​ 本文主要是介绍前后端分离的上传下载,后端使用的是SpringBoot,持久层用的是mybatis-plus,前端用的Vue,UI用的elementUI,测试了一下,文本,图片,excel ...

  9. SpringBoot入门一:基础知识(环境搭建、注解说明、创建对象方法、注入方式、集成jsp/Thymeleaf、logback日志、全局热部署、文件上传/下载、拦截器、自动配置原理等)

    SpringBoot设计目的是用来简化Spring应用的初始搭建以及开发过程.该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置.通过这种方式,SpringBoot致力于在蓬勃发 ...

随机推荐

  1. codevs——T1169 传纸条

    http://codevs.cn/problem/1169/  时间限制: 1 s  空间限制: 128000 KB  题目等级 : 钻石 Diamond 题解  查看运行结果     题目描述 De ...

  2. mysqldump中使用flush tables with read lock的风险分析

      http://blog.csdn.net/wireless_tech/article/details/7332906   我们使用mysqldump --single-transaction -- ...

  3. Seaside HDU 3665 【Dijkstra】

    Problem Description XiaoY is living in a big city, there are N towns in it and some towns near the s ...

  4. study reference

    CVPR2018 ReID论文简评 2017CVPR ICCV和NIPS在Person Reidentification方向的相关工作小结 CVPR 2018 Person Re-ID相关论文 pre ...

  5. Justinmind使用教程(1)——概述部分

    Justinmind(http://www.justinmind.com/),类似于Axure的一个原型设计工具.就眼下而言,最适合移动端进行原型设计的工具,预计抛开Axure几条街了,可是眼下国内站 ...

  6. JVM中java类的载入时机

    Java虚拟机把描写叙述类的数据从Class文件载入到内存.并对数据进行校验.转换解析和初始化.终于形成能够被虚拟机直接使用的Java类型.这就是虚拟机的载入机制. 类从被载入到虚拟机内存中開始,到卸 ...

  7. POJ3204 Ikki's Story - Road Reconstruction 网络流图的关键割边

    题目大意:一个有源有汇的城市,问最少增加城市中的多少道路可以增加源到汇上各个路径上可容纳的总车流量增加. 网络流关键割边集合指如果该边的容量增加,整个网络流图中的任意从原点到汇点的路径的流量便可增加. ...

  8. bzoj4465: [Jsoi2013]游戏中的学问

    DP 一个人要么加入一个圈,要么三个人开一圈 #include<cstdio> #include<iostream> #include<cstring> #incl ...

  9. 使用python进行re拆分网页内容

    这里简短的总结一下而不是完全的罗列python的re模块,python的re具有强大的功能,如下是一个从我们学校抓取数据然后拆分的程序,代码如下: import httplib import urll ...

  10. javascript中的分号【;】

    以前一直以为,在编写js代码的时候,如果在代码后面不添加分号,JavaScript会自动填补分号.最近看了权威指南,才突然发现一直理解有误,而且关于分号的使用,还有很多需要注意的地方. 1.分号的省略 ...