Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uploading images via the Magento SOAP API

Tags:

c#

magento

I'm attempting to upload images to a Magento site using the SOAP API with C#.

This is what I have so far, but it isn't working, no exceptions are thrown or anything but when I go and look on the site the image is blank.

Do I need to do the Base64Encode? I only really tried this because this PHP example does something similar. If I try it without I get a SOAP exception with the error message of "Bad Request".

    FileStream fs = File.OpenRead(@"c:\1.jpg");
    StreamReader sr = new StreamReader(fs);

    string fileConent = sr.ReadToEnd();

    byte[] encbuff = Encoding.UTF8.GetBytes(fileConent);
    string enc = Convert.ToBase64String(encbuff);

    var imageEntity = new catalogProductImageFileEntity();
    imageEntity.content = enc;
    imageEntity.mime = "image/jpeg";
    sr.Close();
    fs.Close();

    var entityP = new catalogProductAttributeMediaCreateEntity();
    entityP.file = imageEntity;
    entityP.types = new[] {"image", "small_image", "thumbnail"};
    entityP.position = "0";
    entityP.exclude = "0";

    _m.catalogProductAttributeMediaCreate(MageSessionProvider.GetSession(), SKU, entityP, "default");
like image 229
Dan Avatar asked Jun 12 '09 17:06

Dan


1 Answers

This took me DAYS to work out.... this is how to do it

public void UploadProductImage(string SKU, string path)
        {
            var imageStream = new MemoryStream();

            using (var i = Image.FromFile(@"c:\ProductImages\" + path))   
            {
                       i.Save(imageStream, ImageFormat.Jpeg);
            }
                byte[] encbuff = imageStream.ToArray(); 

            string enc = Convert.ToBase64String(encbuff,0 , encbuff.Length);


            var imageEntity = new catalogProductImageFileEntity();
            imageEntity.content = enc;
            imageEntity.mime = "image/jpeg";
            imageStream.Close();


            var entityP = new catalogProductAttributeMediaCreateEntity();
            entityP.file = imageEntity;
            entityP.types = new[] {"image", "small_image", "thumbnail"};
            entityP.position = "0";
            entityP.exclude = "0";

            _m.catalogProductAttributeMediaCreate(MageSessionProvider.GetSession(), SKU, entityP, "default");
            Console.WriteLine("Image Uploaded");
        }
like image 80
Dan Avatar answered Sep 18 '22 17:09

Dan