我需要用新的產品圖像替換產品圖像。
我需要用新圖像替換位置2中的圖像。
這是我的代碼。
如何更換Magento中的產品圖像?
$position = 2;//this is the image to delete
$file_location = "../WS-Access-000036-Black-2.jpg";
$sku = "WS-Access-000036-Black";
//delete image
$mediaApi = Mage::getModel("catalog/product_attribute_media_api");
$product = Mage::getModel('catalog/product')->loadByAttribute('sku', $sku);
$product_id = $product->getId();
$items = $mediaApi->items($product_id);
foreach($items as $item){
if($item['position']=="$position" or ($position==1 and $item['position']=="0")){
$mediaApi->remove($product_id, $item['file']);//this doesnt remove file from directory
$image_location = Mage::getBaseDir('media') . DS . 'catalog' . DS . 'product' . $item['file'];
unlink ($image_location);//have to use this to delete image from disk because $mediaApi->remove doesn't delete it from disk
break;
}
}
//end delete image
//EVERYTHING UP TO HERE WORKS, THE IMAGE IS DELETED FROM THE DISK AND
//IN THE BACKEND OF THE PRODUCT
//save new image
$pathInfo = pathinfo($file_location);
switch($pathInfo['extension']){
case 'png':
$mimeType = 'image/png';
break;
case 'jpg':
$mimeType = 'image/jpeg';
break;
case 'gif':
$mimeType = 'image/gif';
break;
}
$types = ($position == 1) ? array('image', 'small_image', 'thumbnail') : array();
$newImage = array(
'file' => array(
'content' => base64_encode($file_location),
'mime' => $mimeType,
'name' => pathinfo($sku."-".$position, PATHINFO_FILENAME),
),
'label' => '',
'position' => $position,
'types' => $types,
'exclude' => 0,
);
$media = Mage::getModel('catalog/product_attribute_media_api');
$media->create($sku, $newImage);
//end save new image
我的問題是,當我刪除圖像WS-ACCESS-000036-黑2.JPG從磁盤和產品目錄,然後我添加新的WS-ACCESS-000036-黑2.JPG到它的產品庫加載了舊的WS-Access-000036-Black-2.jpg。
我在想它的緩存問題,但我已經清除了我的緩存,並且舊圖像不斷加載。
當我此行
'name' => pathinfo($sku."-".$position, PATHINFO_FILENAME),
下更改名稱,這只是一切工作正常。
我需要保留原始文件名。
這是怎麼發生的?
我以前試過這個,認爲這是一個緩存問題,但它沒有奏效。 – altoids
您使用CDN嗎?如果是,那麼你需要刷新CDN。 –