我目前正在通过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吗?
我可以将其保存在本地,然后以编程方式上传吗?
答案 0 :(得分:1)
看看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);
}