springboot实现mongodb上传下载

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());



}

猜你喜欢

转载自www.cnblogs.com/zxg-blog/p/10628697.html