php – Magento – 以编程方式从url添加图像?
发布时间:2020-12-13 16:53:41 所属栏目:PHP教程 来源:网络整理
导读:我目前正在编写一个以编程方式添加产品的脚本. 现在我的问题是这个脚本从URL获取图像并将其上传到目录然后将其用作产品图像. 我正在使用Magento 1.9.1. 所以这里是脚本的一部分,它应该从URL获取图像并将其作为产品图像上传到新产品: $product = Mage::getMo
我目前正在编写一个以编程方式添加产品的脚本.
现在我的问题是这个脚本从URL获取图像并将其上传到目录然后将其用作产品图像. 我正在使用Magento 1.9.1. 所以这里是脚本的一部分,它应该从URL获取图像并将其作为产品图像上传到新产品: $product = Mage::getModel('catalog/product')->load($new_product_id); $url = 'http://media.asicdn.com/images/jpgo/6080000/6089330.jpg'; $img = '/media/catalog/product/images/image1.jpg'; file_put_contents($img,file_get_contents($url)); $product->setMediaGallery (array('images'=>array (),'values'=>array ())); $product->addImageToMediaGallery ($img,array ('image','small_image','thumbnail'),false,false); Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID); $product->save(); 当我这样做时,我收到错误: Fatal error: Uncaught exception 'Mage_Core_Exception' with message 'Image does not exist.' in /home/superweb/public_html/sportsdirect/app/Mage.php:595 Stack trace: #0 /home/superweb/public_html/sportsdirect/app/code/core/Mage/Catalog/Model/Product/Attribute/Backend/Media.php(274): Mage::throwException('Image does not ...') #1 /home/superweb/public_html/sportsdirect/app/code/core/Mage/Catalog/Model/Product.php(1047): Mage_Catalog_Model_Product_Attribute_Backend_Media->addImage(Object(Mage_Catalog_Model_Product),'/media/catalog/...',Array,false) #2 /home/superweb/public_html/sportsdirect/SignProduct.php(63): Mage_Catalog_Model_Product->addImageToMediaGallery('/media/catalog/...',false) #3 {main} thrown in /home/superweb/public_html/sportsdirect/app/Mage.php on line 595 产品已创建,但产品没有图像. 解决方法
希望这有帮助
$newProduct = Mage::getModel('catalog/product')->load($productId); $image_url = $data['productImg']; $image_url = str_replace("https://","http://",$image_url); // replace https tp http $image_type = substr(strrchr($image_url,"."),1); //find the image extension $filename = $data['productPartNumber'].'.'.$image_type; //give a new name,you can modify as per your requirement $filepath = Mage::getBaseDir('media') . DS . 'import'. DS . $filename; //path for temp storage folder: ./media/import/ $curl_handle = curl_init(); curl_setopt($curl_handle,CURLOPT_URL,$image_url); curl_setopt($curl_handle,CURLOPT_CONNECTTIMEOUT,2); curl_setopt($curl_handle,CURLOPT_RETURNTRANSFER,1); curl_setopt($curl_handle,CURLOPT_USERAGENT,'Cirkel'); $query = curl_exec($curl_handle); curl_close($curl_handle); Mage::Log('68. File Path ' . $filepath . ',image url ' . $image_url); file_put_contents($filepath,$query); //store the image from external url to the temp storage folder file_get_contents(trim($image_url)) $filepath_to_image = $filepath; if (file_exists($filepath_to_image)) { $newProduct->addImageToMediaGallery($filepath_to_image,array('image',false); $newProduct->save(); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |