Try our conversational search powered by Generative AI!

Upload Image and save it to the assets tab of a ProductContent

Vote:
 

Hi guys, 

I want to upload an image to the assets tab of a Product Content , I have tried the following code but it doesnt work 

var filePath = "C:\\fl.jpg";
var imageExtension = ".jpg";

var contentReferenceToFolder = new ContentReference(112837);
var contentRepository = ServiceLocator.Current.GetInstance();
var newImage = contentRepository.GetDefault(contentReferenceToFolder);

var blobFactory = ServiceLocator.Current.GetInstance();
var byteArrayData = System.IO.File.ReadAllBytes(filePath);

var blob = blobFactory.CreateBlob(newImage.BinaryDataContainer, imageExtension);
using (var s = blob.OpenWrite())
{
var w = new StreamWriter(s);
w.BaseStream.Write(byteArrayData, 0, byteArrayData.Length);
w.Flush();
}

newImage.BinaryData = blob;
newImage.Name = "fl.jpg";
var contentLink = contentRepository.Save(newImage, SaveAction.Publish,AccessLevel.NoAccess);

// get a variant by its code that is equal to the sku here (it's given in the url ) 
var referenceConverter = ServiceLocator.Current.GetInstance();
var code = sku;
var variantLink = referenceConverter.GetContentLink(code);
var repo = ServiceLocator.Current.GetInstance();
var variant = repo.Get(variantLink);

var commerceMedia = new CommerceMedia() { AssetLink = contentLink };

var clone = variant.CreateWritableClone();
clone.Name = "Update";
contentRepository.Save(clone, SaveAction.Publish, AccessLevel.NoAccess);

clone.CommerceMediaCollection.Add(commerceMedia);



#193579
May 31, 2018 17:11
Vote:
 

Which part doesn't work for you?  You would have to save the content after adding the commerce media

#193580
May 31, 2018 18:03
Vote:
 

I want the image to display here but it doesnt 

#193583
May 31, 2018 18:20
Vote:
 

As I said you have to save after, not before. 

#193584
May 31, 2018 18:24
Vote:
 

Now I get this exception :/ 

#193587
May 31, 2018 18:43
Vote:
 

You have to set other property such as GroupName :) 

#193588
May 31, 2018 18:46
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.