How to save image in mongodb with image url?

I have the following question, I need to save an image to mongodb during web scraping. I have a link to an image. I've tried this:

images_binaries = [] # this will store all images data before saving it to mongodb
# save as file on hard disc
urllib.urlretrieve(url, self.album_path + '/' + photo_file_name)
images_binaries.append(open(self.album_path + '/' + photo_file, 'r').read())
....
# after that I append this array of images raw data to Item
post = WaralbumPost()
post['images_binary'] = images_binaries
....

      

Waralbum element code:

from scrapy.item import Item, Field

class WaralbumPost(Item):
    images_binary = Field()

      

But this results in an error when saving mongo: bson.errors.InvalidStringData: strings in documents must be valid UTF-8: '\xff\.....

What's the best way to do this? Could converting the raw image data solve this problem? Maybe scrapy has a wonderful way to save images? thank you for your responses

SOLUTION: I removed the following lines: images_binaries.append (open (self.album_path + '/' + photo_file, 'r'). Read ()) post ['images_binary'] = images_binaries In my WaralbumPost I also store the image url ... Then, in pipelines.py, I get this url and save the image to mongo. pipelines.py code:

class WarAlbum(object):
def __init__(self):
    connection = pymongo.Connection(settings['MONGODB_SERVER'], settings['MONGODB_PORT'])
    db = connection[settings['MONGODB_DB']]
    self.collection = db[settings['MONGODB_COLLECTION']]
    self.grid_fs = gridfs.GridFS(getattr(connection, settings['MONGODB_DB']))

def process_item(self, item, spider):
    links = item['img_links']
    ids = []
    for i, link in enumerate(links):
        mime_type = mimetypes.guess_type(link)[0]
        request = requests.get(link, stream=True)
        _id = self.grid_fs.put(request.raw, contentType=mime_type, filename=item['local_images'][i])
        ids.append(_id)
    item['data_chunk_id'] = ids
    self.collection.insert(dict(item))
    log.msg("Item wrote to MongoDB database %s/%s" %
            (settings['MONGODB_DB'], settings['MONGODB_COLLECTION']),
            level=log.DEBUG, spider=spider)
    return item

      

Hope this will be helpful for someone

+3


source to share


1 answer


use GridFS. Example:



String newFileName = "my-image";
File imageFile = new File("/users/victor/images/image.png");
GridFS gfsPhoto = new GridFS(db, "photo");
GridFSInputFile gfsFile = gfsPhoto.createFile(imageFile);
gfsFile.setFilename(newFileName);
gfsFile.save();

      

+2


source







All Articles