Add product image programmatically

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.
11 years ago
I'm trying to create a product from plugin, however I'm unable to add pictures to it correctly


            var productService = new NopEngine().Resolve<IProductService>();

            var prod = new Product
            {
                Name = "Test product",
                UpdatedOnUtc = DateTime.UtcNow,
                CreatedOnUtc = DateTime.UtcNow,
            };

            var prodPicture = new ProductPicture
            {
                Picture = new Picture
                {
                    IsNew = true,
                    MimeType = "image/jpeg",
                    SeoFilename = "test",
                    PictureBinary = ImageToBinary("test.jpg")
                }
            };

            prod.ProductPictures.Add(prodPicture);

            productService.InsertProduct(prod);


And


public static byte[] ImageToBinary(string imagePath)
        {
            var fileStream = new FileStream(HttpContext.Current.Server.MapPath("~/" + imagePath), FileMode.Open, FileAccess.Read);
            var buffer = new byte[fileStream.Length];
            fileStream.Read(buffer, 0, (int)fileStream.Length);
            fileStream.Close();
            return buffer;
        }


This code creates new product and adds picture to it. However its not my desired picture but rather "no image" from "content/images/default-image.gif" ... What am I missing?
11 years ago
You need to insert the picture.  Check out how ImportManager does it:

\Libraries\Nop.Services\ExportImport\ImportManager.cs

i.e.

        prod.ProductPictures.Add(new ProductPicture()
            {
                Picture = _pictureService.InsertPicture(data, "image/jpeg", _pictureService.GetPictureSeName(name), true),
                DisplayOrder = 1,
            });
11 years ago
That did it thanks!

+1 for ImportManager.cs reference
4 years ago
У меня проблема делаю плагин который наполняет мой каталог товара из системы поставщика

       var product = new Product
            {
                UpdatedOnUtc = DateTime.UtcNow,
                CreatedOnUtc = DateTime.UtcNow,
                Name = productcctv.Name,

                Price = Math.Ceiling(productcctv.Price * nacenka),
                ProductCost = productcctv.Price,
                ShortDescription = productcctv.Compatibility,
                Sku = productcctv.Id,
                ManufacturerPartNumber = productcctv.OriginalNumber,
                VisibleIndividually = true,
                ProductType = ProductType.SimpleProduct,
                AllowCustomerReviews = true,
                ManageInventoryMethod = ManageInventoryMethod.ManageStock,
                // тут включаем опцию доставки
                IsShipEnabled = true

            };

                product.Published = true;
                product.StockQuantity = maxQuantity;
                product.OrderMinimumQuantity = 1;
                product.OrderMaximumQuantity = maxQuantity;


            var prodCategory = new ProductCategory();
            prodCategory.Category = cat;
            prodCategory.Product = product;

            _categoryService.InsertProductCategory(prodCategory);

все работает товар добавляется в нужную категорию но есть следующая проблема

после того как товар добавился, у него не появляется детальной страницы с описанием

но если я через админ панель нажимаю редактировать товар и сохранить то после этой манипуляции появляется страница с детализацией.

В общем посмотрев разметку понял, после добавления продукта таким образом, в списке товара не появляется ссылка на страницу детализации с описанием данной позиции.

подскажите что я должен добавить в код чтоб эта ссылка появилась на страницу детализации.

Заранее спаибо все ветки форума и документацию читал не нашел нечего внятного, так же изучал (Admin/Controllers/productController Create)
This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.