我目前正在通过 Magento (API_v2) 上的自定义 API 创建分组产品。
我的应用程序发送包含我需要的所有信息的 SOAP 请求:
新端点使用
new Mage_Catalog_Model_Product()
,然后我手动调用多个->setAttributeName(value)
,最后-save()
。
通过 Admin Painel 执行此操作,图像存储在 ./media/catalog/product/b/o/image.jpg 内,但我不认为该路径是硬编码的。
我知道方法
$product->setThumbnail($image)
存在于 setBaseImage()
和 setSmallImage()
之间,但我在传递 $image
参数时遇到问题。
在保存之前是否必须将我的 Base64 上传到 CDN?
我可以将其保存在本地然后以某种方式以编程方式上传吗?
看看 magento 核心的这个 api 方法('product_media.create')。它正是您努力实现的目标。
public function create($productId, $data, $store = null, $identifierType = null)
{
$data = $this->_prepareImageData($data);
$product = $this->_initProduct($productId, $store, $identifierType);
$gallery = $this->_getGalleryAttribute($product);
if (!isset($data['file']) || !isset($data['file']['mime']) || !isset($data['file']['content'])) {
$this->_fault('data_invalid', Mage::helper('catalog')->__('The image is not specified.'));
}
if (!isset($this->_mimeTypes[$data['file']['mime']])) {
$this->_fault('data_invalid', Mage::helper('catalog')->__('Invalid image type.'));
}
$fileContent = @base64_decode($data['file']['content'], true);
if (!$fileContent) {
$this->_fault('data_invalid', Mage::helper('catalog')->__('The image contents is not valid base64 data.'));
}
unset($data['file']['content']);
$tmpDirectory = Mage::getBaseDir('var') . DS . 'api' . DS . $this->_getSession()->getSessionId();
if (isset($data['file']['name']) && $data['file']['name']) {
$fileName = $data['file']['name'];
} else {
$fileName = 'image';
}
$fileName .= '.' . $this->_mimeTypes[$data['file']['mime']];
$ioAdapter = new Varien_Io_File();
try {
// Create temporary directory for api
$ioAdapter->checkAndCreateFolder($tmpDirectory);
$ioAdapter->open(array('path'=>$tmpDirectory));
// Write image file
$ioAdapter->write($fileName, $fileContent, 0666);
unset($fileContent);
// try to create Image object - it fails with Exception if image is not supported
try {
new Varien_Image($tmpDirectory . DS . $fileName);
} catch (Exception $e) {
// Remove temporary directory
$ioAdapter->rmdir($tmpDirectory, true);
throw new Mage_Core_Exception($e->getMessage());
}
// Adding image to gallery
$file = $gallery->getBackend()->addImage(
$product,
$tmpDirectory . DS . $fileName,
null,
true
);
// Remove temporary directory
$ioAdapter->rmdir($tmpDirectory, true);
$gallery->getBackend()->updateImage($product, $file, $data);
if (isset($data['types'])) {
$gallery->getBackend()->setMediaAttribute($product, $data['types'], $file);
}
$product->save();
} catch (Mage_Core_Exception $e) {
$this->_fault('not_created', $e->getMessage());
} catch (Exception $e) {
$this->_fault('not_created', Mage::helper('catalog')->__('Cannot create image.'));
}
return $gallery->getBackend()->getRenamedImage($file);
}