November Happy Hour will be moved to Thursday December 5th.

Using the BlobFactory to store images

Vote:
 

Hi.

I'm trying to store an image with the BlobFactory, but I'm obviously doing something wrong. The image gets stored, but when I try to download it. The image viewer on my machine says it either too large or corrupted. It's probably corrupted, because before I upload the picture I can view it in the image viewer.

This is my code:

var file = _contentRepository.Service.GetDefault(SiteDefinition.Current.GlobalAssetsRoot);
			file.Name = httpPostedFileBase.FileName;
			var blob = _blobFactory.Service.CreateBlob(file.BinaryDataContainer, Path.GetExtension(httpPostedFileBase.FileName));
			using (var s = blob.OpenWrite())
			using (var sw = new StreamWriter(s))
			using (var sr = new BinaryReader(httpPostedFileBase.InputStream))
			{
				sw.Write(sr.ReadBytes(Convert.ToInt32(httpPostedFileBase.InputStream.Length)));
			}
			file.BinaryData = blob;
			return _contentRepository.Service.Save(file, SaveAction.Publish, AccessLevel.NoAccess);

I've been following this post. In this example he only stores text to a .txt file, which is not what I need.

I've tried to use a StreamReader and .ReadToEnd and that returns a string. I've also tried the BinaryReader (as shown in the code above), but no luck there either.

Does anyone know how to store images properly?

// Anders

#88374
Jul 10, 2014 10:37
Vote:
 

Here's some sample code that I've used in the past:

HttpPostedFileBase uploadedFile = Request.Files[i];

if (uploadedFile == null || uploadedFile.ContentLength == 0)
{
	continue;
}

var genericMedia = this._contentRepository.GetDefault(rootFolderContentReference);

genericMedia.Name = uploadedFile.FileName;
var blob = this._blobFactory.CreateBlob(genericMedia.BinaryDataContainer, Path.GetExtension(genericMedia.Name));

blob.Write(uploadedFile.InputStream);

genericMedia.BinaryData = blob;
this._contentRepository.Save(genericMedia, SaveAction.Publish, AccessLevel.NoAccess);

Hope it helps.

Frederik

#88380
Jul 10, 2014 11:39
Vote:
 

This worked. In the example in the post I followed, the Blob needs to be opened for writing first and then use a StreamWriter to write to the blob, but you're just writing directly and it works. Why is that?

Thank you so much for your help, Frederik.

// Anders

#88384
Jul 10, 2014 12:32
This topic was created over six months ago and has been resolved. If you have a similar question, please create a new topic and refer to this one.
* You are NOT allowed to include any hyperlinks in the post because your account hasn't associated to your company. User profile should be updated.