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(图片压缩)上传产品到数据库的过程的更多相关文章

  1. 基于vue + axios + lrz.js 微信端图片压缩上传

    业务场景 微信端项目是基于Vux + Axios构建的,关于图片上传的业务场景有以下几点需求: 1.单张图片上传(如个人头像,实名认证等业务) 2.多张图片上传(如某类工单记录) 3.上传图片时期望能 ...

  2. 三款不错的图片压缩上传插件(webuploader+localResizeIMG4+LUploader)

    涉及到网页图片的交互,少不了图片的压缩上传,相关的插件有很多,相信大家都有用过,这里我就推荐三款,至于好处就仁者见仁喽: 1.名气最高的WebUploader,由Baidu FEX 团队开发,以H5为 ...

  3. Html5+asp.net mvc 图片压缩上传

    在做图片上传时,大图片如果没有压缩直接上传时间会非常长,因为有的图片太大,传到服务器上再压缩太慢了,而且损耗流量. 思路是将图片抽样显示在canvas上,然后用通过canvas.toDataURL方法 ...

  4. 纯原生js移动端图片压缩上传插件

    前段时间,同事又来咨询一个问题了,说手机端动不动拍照就好几M高清大图,上传服务器太慢,问问我有没有可以压缩图片并上传的js插件,当然手头上没有,别慌,我去网上搜一搜. 结果呢,呵呵...诶~又全是基于 ...

  5. springMVC多图片压缩上传的实现

    首先需要在配置文件中添加配置: <!--配置文件的视图解析器,用于文件上传,其中ID是固定的:multipartResolver--> <bean id="multipar ...

  6. 基于H5+ API手机相册图片压缩上传

    // 母函数 function App(){} /** * 图片压缩,默认同比例压缩 * @param {Object} path * pc端传入的路径可以为相对路径,但是在移动端上必须传入的路径是照 ...

  7. 分享图片压缩上传demo,可以选择一张或多张图片也可以拍摄照片

    2016-08-05更新: 下方的代码是比较OLD的了,是通过js进行图片的剪切 旋转 再生成,效率较低. 后来又整合了一个利用native.js本地接口的压缩代码 ,链接在这 .页面中有详细的说明, ...

  8. js 图片压缩上传(base64位)以及上传类型分类

    一.input file上传类型 1.指明只需要图片 <input type="file" accept='image/*'> 2.指明需要多张图片 <input ...

  9. thinkphp + 美图秀秀api 实现图片裁切上传,带数据库

    思路: 1.数据库 创建test2 创建表img,字段id,url,addtime 2.前台页: 1>我用的是bootstrap 引入必要的js,css 2>引入美图秀秀的js 3.后台: ...

随机推荐

  1. Android应用开发进阶篇-场景文字识别

    因为研究生毕业项目须要完毕一个基于移动终端的场景文字识别系统.尽管离毕业尚早,但出于兴趣的缘故,近一段抽时间完毕了这样一套系统. 主要的架构例如以下: client:Android应用实现拍摄场景图片 ...

  2. 约瑟夫环问题的链表解法和数学解法(PHP)

    约瑟夫环问题 一群猴子排成一圈.按1,2,-,n依次编号.然后从第1仅仅開始数,数到第m仅仅,把它踢出圈.从它后面再開始数,再数到第m仅仅.在把它踢出去-.如此不停的进行下去.直到最后仅仅剩下一仅仅猴 ...

  3. 【SDOI 2008】 仪仗队

    [题目链接] https://www.lydsy.com/JudgeOnline/problem.php?id=2190 [算法] 同POJ3090 值得注意的是此题数据规模较大,建议使用用线性筛筛出 ...

  4. 分布式系统CAP原则与BASE思想

    一.CAP原则 CAP原则又称CAP定理,指的是在一个分布式系统中, Consistency(一致性). Availability(可用性).Partition tolerance(分区容错性),三者 ...

  5. 架构-Eureka:第一个方法

    ylbtech-架构-Eureka:第一个方法 工程介绍 Spring Cloud 工程目录 model registry-center Servers tzxyfx tzxyfx-provider ...

  6. k8s istio 配置请求的路由规则

    使用istio我们可以根据权重和HTTP headers来动态配置请求路由. 基于内容的路由 因为BookInfo示例部署了3个版本的评论微服务,我们需要设置一个默认路由. 否则,当你多次访问应用程序 ...

  7. [源码管理] Windows下搭建SVN服务器

    前文所述SVN客户端使用的时候,用的SVN服务器通常为外部,例如Google Code的服务器,不过,做为一个程序开发人员,就算自己一个人写程序,也应该有一个SVN版本控制系统,以便对开发代码进行有效 ...

  8. docker(二):CentOS安装docker

    前置条件 1. CentOS 7:要求系统为64位.系统内核版本为 3.10 以上 使用如下命令,查看机器配置 lsb_release -a uname -a 2. 关闭防火墙 systemctl s ...

  9. python基本数据类型之元祖tuple

    元祖tuple 是对列表的二次加工,书写格式为括号(),里面放元素 元组的一级元素不可被修改,且不能被增加和删除 一般写元组的时候,推荐在最后加入逗号,  能加则加 创建元组 ? 1 tu = (11 ...

  10. guice基本使用,配置模块的两种方式(三)

    guice是使用module进行绑定的,它提供了两种方式进行操作. 第一种是继承AbstractModule抽象类. package com.ming.user.test; import com.go ...