MongoDB上传、下载图片实践

/**
 * 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 list = gfsPhoto.find(fileName);
           if(list.size()>0) {
                for(int i=0;i

上传示例:

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

你可能感兴趣的:(MongoDB上传、下载图片实践)