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))
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?
Here's some sample code that I've used in the past:
HttpPostedFileBase uploadedFile = Request.Files[i];
if (uploadedFile == null || uploadedFile.ContentLength == 0)
var genericMedia = this._contentRepository.GetDefault(rootFolderContentReference);
genericMedia.Name = uploadedFile.FileName;
var blob = this._blobFactory.CreateBlob(genericMedia.BinaryDataContainer, Path.GetExtension(genericMedia.Name));
genericMedia.BinaryData = blob;
this._contentRepository.Save(genericMedia, SaveAction.Publish, AccessLevel.NoAccess);
Hope it helps.
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.