当前位置:   article > 正文

Mongodb GridFS中对文件的上传、下载、删除_docker mongodb gridfs文件下载命令

docker mongodb gridfs文件下载命令

  因为公司之前电商系统的图片存储用的是mongodb,所以昨天讨论后把原定的fastfds改用为mongodb的gridfs。

 mongodb的分片机制也是高可用,高可扩展的。

 mongodb3.2 api地址

 maven地址:

 

  1. <dependency>
  2. <groupId>org.mongodb</groupId>
  3. <artifactId>mongo-java-driver</artifactId>
  4. <version>3.2.2</version>
  5. </dependency>

 

 

 

下面是工具类

 

  1. package com.yjy.dg.app.log.mongo;
  2. import com.mongodb.MongoClient;
  3. import com.mongodb.MongoClientOptions;
  4. import com.mongodb.MongoCredential;
  5. import com.mongodb.ServerAddress;
  6. import com.mongodb.client.MongoDatabase;
  7. import com.mongodb.client.gridfs.GridFSBucket;
  8. import com.mongodb.client.gridfs.GridFSBuckets;
  9. import com.mongodb.client.gridfs.GridFSDownloadStream;
  10. import com.mongodb.client.gridfs.model.GridFSFile;
  11. import com.yjy.dg.app.log.utils.CommonUtil;
  12. import org.bson.types.ObjectId;
  13. import org.slf4j.Logger;
  14. import org.slf4j.LoggerFactory;
  15. import java.io.*;
  16. import java.net.URL;
  17. import java.util.ArrayList;
  18. import java.util.List;
  19. import java.util.Properties;
  20. import java.util.UUID;
  21. import java.util.regex.Pattern;
  22. /**
  23. * MongoDbUtil use mongo-java-driver-3.2.2 gridfs *
  24. * @author littlehow
  25. * @time 2016-07-19 9:18
  26. */
  27. public class MongoDbUtil {
  28. private MongoDbUtil(){}
  29. private final static Properties properties = new Properties();
  30. private static Logger log = LoggerFactory.getLogger(MongoDbUtil.class);
  31. static {
  32. try {
  33. URL url = MongoDbUtil.class.getClassLoader().getResource("mongo_db.properties");
  34. if (url != null) {
  35. log.info("Found 'mongo_db.properties' file in local classpath");
  36. InputStream in = url.openStream();
  37. try {
  38. properties.load(in);
  39. } finally {
  40. in.close();
  41. }
  42. }
  43. } catch (IOException e) {
  44. log.info("Could not load 'mongo_db.properties' file from local classpath: " + e);
  45. }
  46. }
  47. /**
  48. * config file info
  49. */
  50. private static class Config {
  51. //mongodb connection properties
  52. public static String ip = null;
  53. //default port is 27017
  54. public static int port = 27017;
  55. public static String database = null;
  56. //mongodb connection pool properties
  57. public static int connectionsPerHost = 10;
  58. public static int maxWaitTime = 120000;
  59. public static int connectTimeout = 0;
  60. public static MongoClientOptions options = null;
  61. //author
  62. public static List<MongoCredential> credential = new ArrayList<>();
  63. static {
  64. ip = properties.getProperty("mongo_ip");
  65. database = properties.getProperty("mongo_database");
  66. int _port = CommonUtil.getIntValue(properties.getProperty("mongo_port"));
  67. if (_port != -1) port = _port; int _conn = CommonUtil.getIntValue(properties.getProperty("connections_per_host"));
  68. if (_conn != -1) connectionsPerHost = _conn;
  69. int _waittime = CommonUtil.getIntValue(properties.getProperty("max_wait_time"));
  70. if (_waittime != -1) maxWaitTime = _waittime;
  71. int _timeout = CommonUtil.getIntValue(properties.getProperty("connect_timeout"));
  72. if (_timeout != -1) connectTimeout = _timeout;
  73. options = MongoClientOptions.builder().connectTimeout(connectTimeout) .maxWaitTime(maxWaitTime).connectionsPerHost(connectionsPerHost).build();
  74. MongoCredential credential1 = MongoCredential.createCredential(properties.getProperty("mongo_user"), database, properties.getProperty("mongo_pass").toCharArray());
  75. credential.add(credential1);
  76. }
  77. }
  78. private static final class MongoInstance {
  79. public final static MongoClient client;
  80. static {
  81. client = new MongoClient(new ServerAddress(Config.ip, Config.port), Config.credential, Config.options);
  82. }
  83. }
  84. /**
  85. * destroy pool
  86. */
  87. public static final void destroy() {
  88. MongoInstance.client.close();
  89. }
  90. /**
  91. * get a MongoDatabase
  92. * @return
  93. */
  94. public static MongoDatabase getDatabase() {
  95. return MongoInstance.client.getDatabase(Config.database);
  96. }
  97. /**
  98. * get a MongoDatabase by Name
  99. * @param databaseName
  100. * @return
  101. */
  102. public static MongoDatabase getDatabase(String databaseName) {
  103. return MongoInstance.client.getDatabase(databaseName);
  104. }
  105. /**
  106. * upload file to mongo
  107. * @param filename
  108. * @param in
  109. * @return
  110. */
  111. public static String uploadFileToGridFS(String filename, InputStream in) {
  112. //default bucket name is fs
  113. GridFSBucket bucket = GridFSBuckets.create(getDatabase());
  114. ObjectId fileId = bucket.uploadFromStream(filename, in);
  115. return fileId.toHexString();
  116. }
  117. /**
  118. * upload file to mongo, if close is true then close the inputstream
  119. * @param filename
  120. * @param in
  121. * @param close
  122. * @return
  123. */
  124. public static String uploadFileToGridFS(String filename, InputStream in, boolean close) {
  125. String returnId = null;
  126. try {
  127. returnId = uploadFileToGridFS(filename, in);
  128. } finally {
  129. if (close) {
  130. try {
  131. in.close();
  132. } catch (IOException e) {
  133. log.info("close inputstream fail:" + e);
  134. }
  135. }
  136. }
  137. return returnId;
  138. }
  139. /**
  140. * upload file to mongo
  141. * @param fileName
  142. * @param file
  143. * @return
  144. */
  145. public static String uploadFileToGridFs(String fileName, File file) {
  146. InputStream in = null;
  147. try {
  148. in = new FileInputStream(file);
  149. String returnId = uploadFileToGridFS(fileName, in, true);
  150. return returnId;
  151. } catch (IOException e) {
  152. log.info("upload fail:" + e);
  153. }
  154. return null;
  155. }
  156. /**
  157. * set filename = file name
  158. * @param file
  159. * @return
  160. */
  161. public static String uploadFileToGridFs(File file) {
  162. return uploadFileToGridFs(file.getName(), file);
  163. }
  164. /**
  165. * set filename = uuid
  166. * @param file
  167. * @return
  168. */
  169. public static String uploadFileToGridFSByUUID(File file) {
  170. return uploadFileToGridFs(UUID.randomUUID().toString(), file);
  171. }
  172. /**
  173. * download file for gridfs by objectid
  174. * @param objectId
  175. * @param out
  176. */
  177. public static void downloadFile(String objectId, OutputStream out) {
  178. GridFSBucket bucket = GridFSBuckets.create(getDatabase());
  179. bucket.downloadToStream(new ObjectId(objectId), out);
  180. }
  181. /**
  182. * download file for gridfs by objectid
  183. * @param objectId
  184. * @param file
  185. */
  186. public static void downloadFile(String objectId, File file) {
  187. OutputStream os = null;
  188. try {
  189. os = new FileOutputStream(file);
  190. downloadFile(objectId, os);
  191. } catch (IOException e) {
  192. log.info("download fail:" + e);
  193. } finally {
  194. if (os != null) {
  195. try {
  196. os.close();
  197. } catch (IOException e) {
  198. log.info("close outputstream fail:" + e);
  199. }
  200. }
  201. }
  202. }
  203. /**
  204. * download file for gridfs by objectid
  205. * @param objectId
  206. * @param filename
  207. */
  208. public static void downloadFile(String objectId, String filename) {
  209. File file = new File(filename);
  210. downloadFile(objectId, file);
  211. }
  212. /**
  213. * download file for gridfs by filename
  214. * @param filename
  215. * @param out
  216. */
  217. public static void downloadFileByName(String filename, OutputStream out) {
  218. GridFSBucket bucket = GridFSBuckets.create(getDatabase());
  219. bucket.downloadToStreamByName(filename, out);
  220. }
  221. /**
  222. * download file for gridfs use stream
  223. * 如果一次性读取所有字节,大于chunk size的可能会出现乱序,导致文件损坏
  224. * @param objectId
  225. * @param out
  226. */
  227. public static void downloadFileUseStream(String objectId, OutputStream out) {
  228. GridFSBucket bucket = GridFSBuckets.create(getDatabase());
  229. GridFSDownloadStream stream = null;
  230. try {
  231. stream = bucket.openDownloadStream(new ObjectId(objectId));
  232. /** gridfs file */
  233. GridFSFile file = stream.getGridFSFile();
  234. /** chunk size */
  235. int size = file.getChunkSize();
  236. int len = (int)file.getLength();
  237. /** loop time */
  238. int cnt = len / size + (len % size == 0 ? 0 : 1);
  239. byte[] bts = new byte[Math.min(len, size)];
  240. try {
  241. while (cnt-- > 0) {
  242. int tmp = stream.read(bts);
  243. out.write(bts, 0, tmp);
  244. }
  245. out.flush();
  246. } catch (IOException e) {
  247. log.info("download fail:");
  248. }
  249. } finally {
  250. if (stream != null) stream.close();
  251. }
  252. }
  253. /**
  254. * download file for gridfs use stream
  255. * @param objectId
  256. * @param fileName
  257. */
  258. public static void downloadFileUseStream(String objectId, String fileName) {
  259. File file = new File(fileName);
  260. downloadFileUseStream(objectId, file);
  261. }
  262. /**
  263. * download file for gridfs use stream
  264. * @param objectId
  265. * @param file
  266. */
  267. public static void downloadFileUseStream(String objectId, File file) {
  268. OutputStream os = null;
  269. try {
  270. os = new FileOutputStream(file);
  271. downloadFileUseStream(objectId, os);
  272. } catch (IOException e) {
  273. log.info("download fail:" + e);
  274. } finally {
  275. if (os != null) {
  276. try {
  277. os.close();
  278. } catch (IOException e) {
  279. // skip
  280. }
  281. }
  282. }
  283. }
  284. /**
  285. * 将mongo gridfs的文件下载到内存
  286. * @param objectId
  287. * @return
  288. */
  289. public static byte[] downloadFileUseStream(String objectId) {
  290. GridFSBucket bucket = GridFSBuckets.create(getDatabase());
  291. GridFSDownloadStream stream = null;
  292. try {
  293. stream = bucket.openDownloadStream(new ObjectId(objectId));
  294. /** gridfs file */
  295. GridFSFile file = stream.getGridFSFile();
  296. /** chunk size */
  297. int size = file.getChunkSize();
  298. int len = (int)file.getLength();
  299. int readSize = Math.min(len, size);
  300. byte[] returnBts = new byte[len];
  301. /** offset num */
  302. int offset = 0;
  303. while (len > 0) {
  304. int tmp;
  305. if (len > readSize) {
  306. tmp = stream.read(returnBts, offset, readSize);
  307. offset += tmp;
  308. } else {
  309. tmp = stream.read(returnBts, offset, len);
  310. }
  311. len -= tmp;
  312. }
  313. return returnBts;
  314. } finally {
  315. if (stream != null) stream.close();
  316. }
  317. }
  318. /**
  319. * delete file from gridfs by objectId
  320. * @param objectId
  321. */
  322. public static void deleteByObjectId(String objectId) {
  323. GridFSBucket bucket = GridFSBuckets.create(getDatabase());
  324. bucket.delete(new ObjectId(objectId));
  325. }
  326. }


 

 

 

 

简单的测试调用:

 

  1. package littlehow.test;
  2. import littlehow.utils.MongoDbUtil;
  3. import java.io.File;
  4. /**
  5. * MongoDbTest
  6. *
  7. * @author littlehow
  8. * @time 2016-07-19 15:13
  9. */
  10. public class MongoDbTest {
  11. public static void main(String[] args) {
  12. // upload();
  13. // download();
  14. delete();
  15. }
  16. /**
  17. * 先上传
  18. */
  19. public static void upload() {
  20. File file = new File("E:\\before\\myself.zip");
  21. String objectId = MongoDbUtil.uploadFileToGridFSByUUID(file);
  22. System.out.println(objectId);//578dccf8b585d81928e6ba62
  23. }
  24. /**
  25. * 再测试下载
  26. */
  27. public static void download() {
  28. File file = new File("C:\\Users\\Administrator\\Desktop\\linshi\\new.zip");
  29. MongoDbUtil.downloadFile("578dccf8b585d81928e6ba62", file);
  30. }
  31. /**
  32. * 最后将上传的信息删除
  33. */
  34. public static void delete() {
  35. MongoDbUtil.deleteByObjectId("578dccf8b585d81928e6ba62");
  36. }
  37. }

 

 

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/220853
推荐阅读
相关标签
  

闽ICP备14008679号