我爱编程

MongoDB上传、下载图片实践

2018-03-14  本文已影响132人  _浅墨_
/**
 * mongodb 上传下载图片工具类
 * @author chang
 *
 */
public class MongoDBUtil {

    private static final Logger LOGGER = Logger.getLogger(MongoDBUtil.class);
    
    @Autowired
    private Mongo mongo;
    /**
     * 上传文件到 MongoDB
     * 
     * @param inputStream
     * @param fileName
     * @param createDate
     * @return
     */
    public void upload(InputStream inputStream, String fileName, String createDate) throws FileUploadException, SocketException, IOException{

        System.out.println("Calling upload...");
        try {
            GridFS gfsPhoto = initMongoDB(); 
            GridFSInputFile gfsFile = gfsPhoto.createFile(inputStream);
            gfsFile.setFilename(fileName); 
            gfsFile.save(); 
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("上传图片到 mongodb 失败:" + e);
            throw new FileUploadException("ERR01");
        } finally {
            this.mongo.close();
        }
    }

    /**
     * 下载文件
     * 
     * @param fileName
     */
    public ByteArrayOutputStream download(String fileName) {
        System.out.println("Calling download...");
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
             GridFS gfsPhoto = initMongoDB(); 
           List<GridFSDBFile> list = gfsPhoto.find(fileName);
           if(list.size()>0) {
                for(int i=0;i<list.size();i++) {
                      GridFSDBFile file = list.get(0);
                  file.writeTo(baos);
               }
           }
        } catch (Exception e) {
            LOGGER.error("下载 mongodb 图片失败:" + e);
            e.printStackTrace();
        } finally {
            this.mongo.close();
        }
        return baos;
    }

    /**
     * 初始化MongoDB
     *
     */
    private GridFS initMongoDB() {
          // 连接到服务
       this.mongo = new Mongo("192.168.22.93", 27017);
       // 连接到数据库
       DB db = this.mongo.getDB("checkInImages");// db name    
         db.setWriteConcern(WriteConcern.SAFE);
       GridFS gfsPhoto = new GridFS(db, "MyImages"); // db collection name
       return gfsPhoto;
    }
}

上传示例:

byte[] redcoeByte = ...;// 要上传的数据流,如图片数据流
InputStream in = new ByteArrayInputStream(redcoeByte);

// 上传到mongodb
String fileName = Md5Encrypt.md5(orderHeadId.toString()) + ".png";

Date now = new Date();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.SIMPLIFIED_CHINESE);
String createDate = df.format(now);

MongoDBUtil mongodb = new MongoDBUtil();
mongodb.upload(in, fileName, createDate);

下载示例:

MongoDBUtil mongoDB = new MongoDBUtil();
ByteArrayOutputStream output = mongoDB.download(fileName+"."+fileType);
        
上一篇下一篇

猜你喜欢

热点阅读