记录magento通过csv文件与zip(图片压缩)上传产品到数据库的过程
1,前台使用input-file type按钮提交文件到magento指定的控制器,controllers获取.csv文件,因为magento是在zend框架上实现的,可以使用如下代码获取文件的上传信息:
/**
* New zend File Uploader
*/
$uploadsData = new Zend_File_Transfer_Adapter_Http ();
$filesDataArray = $uploadsData->getFileInfo ();
2,遍历获取的$filesDataArray文件,这里上传的文件包括:保存产品信息的csv文件与对应的zip产品图片,遍历图片代码如下:
$currentDateTime = date ( "Ymd_His", Mage::getModel ( 'core/date' )->timestamp ( time () ) ); foreach ( $filesDataArray as $key => $value ) {
/**
* Initilize file name
*/
$filename = $key; /**
* Upload csv file
*/ if ($key == 'bulk-product-upload-csv-file' && isset ( $filesDataArray [$filename] ['name'] ) && (file_exists ( $filesDataArray [$filename] ['tmp_name'] ))) {
$csvFilePath = '';
$csvFilePath = array ();
$uploader = new Varien_File_Uploader ( $filename );
$uploader->setAllowedExtensions ( array (
'csv'
) );
$uploader->setAllowRenameFiles ( true );
$uploader->setFilesDispersion ( false );
$path = Mage::getBaseDir ( 'media' ) . DS . 'marketplace' . DS . 'bulk' . DS . 'product' . DS . 'csv' . DS; $uploader->save ( $path, 'seller_' . $sellerId . '_date_' . $currentDateTime . '.csv' );
$csvFilePath = $path . $uploader->getUploadedFileName ();
} /**
* Upload csv image
*/
if ($key == 'bulk-product-upload-image-file' && isset ( $filesDataArray [$filename] ['name'] ) && (file_exists ( $filesDataArray [$filename] ['tmp_name'] ))) {
$uploader = new Varien_File_Uploader ( $filename );
$uploader->setAllowedExtensions ( array (
'zip'
) );
$uploader->setAllowRenameFiles ( true );
$uploader->setFilesDispersion ( false );
$path = Mage::getBaseDir ( 'media' ) . DS . 'marketplace' . DS . 'bulk' . DS . 'product' . DS . 'image' . DS;
/**
* Uploader save
*/
$uploader->save ( $path, 'seller_' . $sellerId . '_date_' . $currentDateTime . '.zip' );
$imageFilePath = $path . $uploader->getUploadedFileName (); $ZipFileName = $imageFilePath;
$homeFolder = Mage::getBaseDir ( 'media' ) . DS . 'marketplace' . DS . 'bulk' . DS . 'product' . DS . 'image' . DS . 'seller_' . $sellerId . '_date_' . $currentDateTime;
/**
* New Varien File
*/
$file = new Varien_Io_File ();
/**
* Make Directory
*/
$file->mkdir ( $homeFolder );
Mage::helper ( 'marketplace/product' )->exportZipFile ( $ZipFileName, $homeFolder );
}
}
在此之中,对遍历到的csv和zip文件分别保存到设置的文件夹下:
对于csv文件设置了存储路径,限制了文件上传的格式,根据商户ID与上传时间设置了文的存储名称:
$uploader->save ( $path, 'seller_' . $sellerId . '_date_' . $currentDateTime . '.csv' );
对于zip的图片文件设置了存储路径,限制了文件上传的格式,根据商户ID与上传时间设置了文的存储名称:
$uploader->save ( $path, 'seller_' . $sellerId . '_date_' . $currentDateTime . '.zip' );
$imageFilePath = $path . $uploader->getUploadedFileName ();
$ZipFileName = $imageFilePath;
解压zip图片,用使用当前模块中helper=>exportZipFile ( $ZipFileName, $homeFolder )对上传的zip图片进行解压,代码如下:
/**
*
*
*
* Unzip uploaded images
*
* @param string $zipFileName
* @return boolean
*/
public function exportZipFile($zipFileName, $homeFolder) {
/**
* New ZIP archive
*/
$zip = new ZipArchive ();
if ($zip->open ( $zipFileName ) === true) {
/**
* Make all the folders
*/
for($i = 0; $i < $zip->numFiles; $i ++) {
$onlyFileName = $zip->getNameIndex ( $i );
$fullFileName = $zip->statIndex ( $i );
if ($fullFileName ['name'] [strlen ( $fullFileName ['name'] ) - 1] == "/") {
@mkdir ( $homeFolder . "/" . $fullFileName ['name'], 0700, true );
}
} /**
* Unzip into the folders
*/
for($i = 0; $i < $zip->numFiles; $i ++) {
$onlyFileName = $zip->getNameIndex ( $i );
$fullFileName = $zip->statIndex ( $i ); if (! ($fullFileName ['name'] [strlen ( $fullFileName ['name'] ) - 1] == "/") && preg_match ( '#\.(jpg|jpeg|gif|png)$#i', $onlyFileName )) {
copy ( 'zip://' . $zipFileName . '#' . $onlyFileName, $homeFolder . "/" . $fullFileName ['name'] );
}
}
$zip->close ();
} else {
Mage::getSingleton ( 'core/session' )->addError ( $this->__ ( "Error: Can't open zip file" ) );
}
return true;
}
把csv文件转换为数组形式,使用当前模块中helper=>convertCsvFileToUploadArray ( $csvFilePath )进行转换,代码如下:
/**
*
*
*
* Convert csv file to upload array
*
* @param string $csvFilePath
* @return array
*/
public function convertCsvFileToUploadArray($csvFilePath) {
$productInfo = array ();
if (! empty ( $csvFilePath )) {
/**
* Initializing new varien file
*/
$csv = new Varien_File_Csv ();
$data = $csv->getData ( $csvFilePath );
$line = $lines = ''; $keys = array_shift ( $data ); /**
* Getting instance for catalog product collection
*/
$productInfo = $createProductData = array ();
foreach ( $data as $lines => $line ) {
if (count ( $keys ) == count ( $line )) {
$data [$lines] = array_combine ( $keys, $line );
}
} if (count ( $data ) <= 1 && count ( $keys ) >= 1 && ! empty ( $line ) && count ( $keys ) == count ( $line )) {
$data [$lines + 1] = array_combine ( $keys, $line );
} $createProductData = $this->uploadProductData ( $data ); if (! empty ( $createProductData )) {
$productInfo [] = $createProductData;
}
} return $productInfo;
}
只要是获取csv表格头部的命名(数据库字段)使用 $data [$lines] = array_combine ( $keys, $line ),转换为以下标为字段名,对应为值得二维数组
3,使用一下方法处理收集到的数据,代码如下:
/**
*
* @param string $imageFilePath
* @param array $productData
* @param string $homeFolder
* @param string $csvFilePath
* @return boolean
*/
public function bulkproductuploadfuncationality($imageFilePath, $productData, $homeFolder, $csvFilePath) {
if (file_exists ( $imageFilePath )) {
/**
* Delete images from temporary zip folder
*/
unlink ( $imageFilePath );
} if (isset ( $productData [0] )) {
$configurableAttributes = array ();
/**
* Get Configurable Products
*/
$configurableAttributes = $this->getRequest ()->getPost ( 'configurable_attribute' );
Mage::helper ( 'marketplace/image' )->saveProductData ( $productData [0], $homeFolder, $configurableAttributes );
if (Mage::getStoreConfig ( 'marketplace/product/save_uploadfiles' ) != 1) {
if (file_exists ( $csvFilePath )) {
/**
* Delete csv file
*/
unlink ( $csvFilePath );
} /**
* Delete images from temporary zip folder
*/
Mage::helper ( 'marketplace/image' )->rrmdir ( $homeFolder );
}
$this->_redirect ( 'marketplace/product/manage/' );
} else {
/**
* Add Notice
*/
Mage::getSingleton ( 'core/session' )->addNotice ( Mage::helper ( 'marketplace' )->__ ( 'No data found' ) );
$this->_redirect ( 'marketplace/product/manage/' );
return true;
}
}
对于zip的图片文件进行删除,并使用saveProductData($productData, $imagePath, $configurableAttributes) 对存储数据的结果进行消息返回提示,在此之中会提示重复的sku,gtin码的验证结果及是否重复,或者上传成功产品数量,此方法中使用saveBulkUploadProduct ( $productData, $imagePath,$configurableAttributes, $rowcountForImport )对产品信息存入数据库,代码如下:
/**
* Save bulk upload product
*
* @param array $productData
* @param array $imagePath
* @param array $configurableAttributes
* @param number $rowcountForImport
* @return array $productCountArray
*/
public function saveBulkUploadProduct($productData, $imagePath, $configurableAttributes, $rowcountForImport) {
$countries = Mage::getModel ( 'marketplace/bulk' )->getContriesValue ();
/**
* Initilize website ids
*/
$websiteIds = array (
Mage::app ()->getStore ( true )->getWebsite ()->getId ()
);
$importProductsCount = 0;
$existSkuCounts = 0;
$existGtinCounts = 0;
$notValidGtinsCounts = 0;
$existGtinLists = array();
$notValidGtinsArr=array();
$productCountArray = array ();
foreach ( $productData ['sku'] as $key => $value ) {
$flag = Mage::getModel ( 'marketplace/bulk' )->checkRequiredFieldForBulkUpload ( $productData, $key );
if ($flag == 1) {
$images = array ();
$checkSkuAndGtinModel= Mage::getModel ( 'catalog/product' );
$productSkuForCheck =$checkSkuAndGtinModel->getIdBySku ( $productData ['sku'] [$key] );
if ($productSkuForCheck) {
$existSkuCounts = $existSkuCounts + 1;
continue;
}
$gtinCode= $productData ['gtin'] [$key];
$collection =$checkSkuAndGtinModel->getCollection ()->addAttributeToFilter ( 'gtin', $gtinCode );
$count = count ( $collection );
if($count){
$existGtinLists[]=$gtinCode;
$existGtinCounts=$existGtinCounts+1;
continue;
}
if(!preg_match('/^[0-9]{12,13}$ /', $gtinCode)){
$notValidGtinsArr[]=$gtinCode;
$notValidGtinsCounts=$notValidGtinsCounts+1;
continue;
}
$orFlag = Mage::getModel ( 'marketplace/bulk' )->checkProductTypeForBulkUpload ( $productData, $key );
if ($orFlag == 1) {
$product = Mage::getModel ( 'catalog/product' );
$categoryIds = array ();
/**
* Multi row product data
*/
$attributeSetName = $productData ['_attribute_set'] [$key];
$sku = $productData ['sku'] [$key];
$name = $productData ['name'] [$key];
$gtin = $productData ['gtin'] [$key];
$description = $productData ['description'] [$key];
$shortDescription = $productData ['short_description'] [$key];
$price = $productData ['price'] [$key];
$type = $productData ['_type'] [$key];
$weight = Mage::getModel ( 'marketplace/bulk' )->getWeightForBulkUpload ( $productData, $key, $type );
/**
* Getting special price values
*/
$specialPrice = $productData ['special_price'] [$key];
$specialDate = array ();
$specialDate ['special_from_date'] = $productData ['special_from_date'] [$key];
$specialDate ['special_to_date'] = $productData ['special_to_date'] [$key];
/**
* Fetch images info for product
*/
$images = Mage::getModel ( 'marketplace/bulk' )->getImagesForBulkProduct ( $key, $productData );
$categoryIds = Mage::getModel ( 'marketplace/bulk' )->getCategoryIdsForBulk ( $key, $productData );
$customOptions = Mage::getModel ( 'marketplace/bulk' )->getCustomOptionsForBulk ( $key, $productData, $rowcountForImport );
$dataForBulkUpload = Mage::getModel ( 'marketplace/bulk' )->getDataForBulkProduct ( $key, $productData );
/**
* Fetch attribute set id by attribute set name
*/
$entityTypeId = Mage::getModel ( 'eav/entity' )->setType ( 'catalog_product' )->getTypeId ();
$attributeSetId = Mage::getModel ( 'eav/entity_attribute_set' )->getCollection ()->setEntityTypeFilter ( $entityTypeId )->addFieldToFilter ( 'attribute_set_name', $attributeSetName )->getFirstItem ()->getAttributeSetId (); if (empty ( $attributeSetId )) {
$attributeSetId = Mage::getModel ( 'eav/entity_attribute_set' )->getCollection ()->setEntityTypeFilter ( $entityTypeId )->addFieldToFilter ( 'attribute_set_name', 'Default' )->getFirstItem ()->getAttributeSetId ();
} $product->setSku ( $sku );
$product->setName ( $name );
$product->setGtin ( $gtin );
$product->setDescription ( $description );
$product->setShortDescription ( $shortDescription );
$product->setPrice ( $price );
/**
* Set product data for bulk product upload
*/
$product = Mage::getModel ( 'marketplace/bulk' )->setProductDataForBulkProductUpload ( $product, $specialPrice, $specialDate, $type, $weight, $attributeSetId, $categoryIds );
$product = Mage::getModel ( 'marketplace/bulk' )->setProductInfoForBulkProductUpload ( $dataForBulkUpload, $productData, $key, $product, $websiteIds, $countries );
$product = Mage::getModel ( 'marketplace/bulk' )->setImagesAndCustomOptionForBulkProductUpload ( $product, $images, $imagePath, $customOptions );
/**
* Fetch configurable product options
*/
$configurableProductsDataBulk = Mage::getModel ( 'marketplace/bulk' )->getConfigurableProductDataForBulkUpload ( $key, $type, $productData );
$attributeIds = $configurableProductsDataBulk ['attribute_ids'];
$configurableProductsData = $configurableProductsDataBulk ['configurable_products_data'];
$superProductsSkus = $configurableProductsDataBulk ['super_products_skus'];
$product = Mage::getModel ( 'marketplace/bulk' )->setConfigurableProductDataForBulkUpload ( $product, $attributeIds, $type, $attributeSetId, $configurableProductsData );
$product = Mage::getModel ( 'marketplace/bulk' )->setProductConfigData ( $productData, $product, $configurableAttributes, $key ); /**
* Initialize configurable product options
*/
$product->save ();
Mage::getModel ( 'marketplace/bulk' )->saveSimpleProductForBulkUpload ( $type, $superProductsSkus, $product ); Mage::getSingleton ( 'catalog/product_option' )->unsetOptions ();
$importProductsCount = $importProductsCount + 1;
}
}
}
/**
* Initilize rpoduct count array
*/
$productCountArray ['import_products_count'] = $importProductsCount;
$productCountArray ['exist_sku_counts'] = $existSkuCounts;
$productCountArray ['exist_gtin_counts'] = $existGtinCounts;
$productCountArray ['exist_gtin_lists'] = $existGtinLists;
$productCountArray ['not_valid_gtin_counts'] = $notValidGtinsCounts;
$productCountArray ['not_valid_gtin_lists'] = $notValidGtinsArr;
return $productCountArray;
}
在此之中,会用到magento特有的model方法,把数据存入数据库,最常用的collection,resource等
总结:整个过程下来,一个模块中的model,helper方法混合调用,使用magento特有的model方法操作数据比较方便,使用zend框架处理文件上传与csv文件转数据也比较省事
记录magento通过csv文件与zip(图片压缩)上传产品到数据库的过程的更多相关文章
- 基于vue + axios + lrz.js 微信端图片压缩上传
业务场景 微信端项目是基于Vux + Axios构建的,关于图片上传的业务场景有以下几点需求: 1.单张图片上传(如个人头像,实名认证等业务) 2.多张图片上传(如某类工单记录) 3.上传图片时期望能 ...
- 三款不错的图片压缩上传插件(webuploader+localResizeIMG4+LUploader)
涉及到网页图片的交互,少不了图片的压缩上传,相关的插件有很多,相信大家都有用过,这里我就推荐三款,至于好处就仁者见仁喽: 1.名气最高的WebUploader,由Baidu FEX 团队开发,以H5为 ...
- Html5+asp.net mvc 图片压缩上传
在做图片上传时,大图片如果没有压缩直接上传时间会非常长,因为有的图片太大,传到服务器上再压缩太慢了,而且损耗流量. 思路是将图片抽样显示在canvas上,然后用通过canvas.toDataURL方法 ...
- 纯原生js移动端图片压缩上传插件
前段时间,同事又来咨询一个问题了,说手机端动不动拍照就好几M高清大图,上传服务器太慢,问问我有没有可以压缩图片并上传的js插件,当然手头上没有,别慌,我去网上搜一搜. 结果呢,呵呵...诶~又全是基于 ...
- springMVC多图片压缩上传的实现
首先需要在配置文件中添加配置: <!--配置文件的视图解析器,用于文件上传,其中ID是固定的:multipartResolver--> <bean id="multipar ...
- 基于H5+ API手机相册图片压缩上传
// 母函数 function App(){} /** * 图片压缩,默认同比例压缩 * @param {Object} path * pc端传入的路径可以为相对路径,但是在移动端上必须传入的路径是照 ...
- 分享图片压缩上传demo,可以选择一张或多张图片也可以拍摄照片
2016-08-05更新: 下方的代码是比较OLD的了,是通过js进行图片的剪切 旋转 再生成,效率较低. 后来又整合了一个利用native.js本地接口的压缩代码 ,链接在这 .页面中有详细的说明, ...
- js 图片压缩上传(base64位)以及上传类型分类
一.input file上传类型 1.指明只需要图片 <input type="file" accept='image/*'> 2.指明需要多张图片 <input ...
- thinkphp + 美图秀秀api 实现图片裁切上传,带数据库
思路: 1.数据库 创建test2 创建表img,字段id,url,addtime 2.前台页: 1>我用的是bootstrap 引入必要的js,css 2>引入美图秀秀的js 3.后台: ...
随机推荐
- ubuntu下创建第一个rails应用程序
一.创建一个新的应用程序 在控制台输入 > rails new demo create create README.rdoc create Rakefile create config.ru ...
- bzoj5029: 贴小广告&&bzoj5168: [HAOI2014]贴海报
以后做双精题请至少先跑个数据...输入都不一样... 做法就是离散化大力线段树. 记得在x+1和y-1插点 看这个数据: 1000 121 10050 8080 9950 981 56100 2002 ...
- 深度学习实战篇-基于RNN的中文分词探索
深度学习实战篇-基于RNN的中文分词探索 近年来,深度学习在人工智能的多个领域取得了显著成绩.微软使用的152层深度神经网络在ImageNet的比赛上斩获多项第一,同时在图像识别中超过了人类的识别水平 ...
- 【概率证明】—— sum and product rules of probability
1. sum and product rules of probability ⎧⎩⎨p(x)=∫p(x,y)dyp(x,y)=p(x|y)p(y) sum rule of probability 的 ...
- 2.TinkPHP入门----控制器
1.控制器创建 命名规则:控制器名称+Controller+.class.php, 例如GoodsController.class.php UserController.class.php 控制器结 ...
- SSRS 报表 如何加参数
SSRS 报表 如何加参数 连接上以后出现一个问题 就是给报表加上参数以后报表不断刷新,跟上次那个报表刷新是同样的问题.那么下面我们来解决一下. 1. 这是给报表添加默认参数进入页面后就不断的刷新刷新 ...
- shopping car 2.0
#!/usr/bin/env python# -*- coding: utf-8 -*-# @Time : 2018/5/13 0013 10:20# @Author : Anthony.Waa# @ ...
- 在Hibernate映射文件里配置Sequence
<!--注意该id的数据类型以及<generator>节点下的<param>节点的写法--> <id name="id" type=&qu ...
- 第5章分布式系统模式 在 .NET 中使用 DataSet 实现 Data Transfer Object
要在 .NET Framework 中实现分布式应用程序.客户端应用程序需要显示一个窗体,该窗体要求对 ASP.NET Web Service 进行多个调用以满足单个用户请求.基于性能方面的考虑,我们 ...
- 【MFC】如何在mfc窗口程序中调用控制台
1.工程名为Zero,在CZeroDlg.cpp中加入头文件 #include “conio.h” : 2.在CZeroDlg::OnInitDialog() {…}函数中加入AllocConsole ...