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. ArcGIS Python实现Modis NDVI批量化月最大合成

    最大合成法(MVC)能够在Envi中的Band Math中进行,式子是B1>B2,可是无法批量化.本文实如今ArcGIS中利用Python代码批量进行,例如以下: 用到的Modis NDVI数据 ...

  2. [转]详细解读TrueSkill 排名系统

    概要 大多数竞技游戏都有一个评价玩家是否完成目标的度量指标,它是游戏的基础.对于包含两个或两个以上玩家(多玩家比赛)的比赛,常涉及到游戏玩家技能的排名方法.游戏鼓励玩家之间相互竞争,玩家不只要赢得单场 ...

  3. 国内物联网平台初探(三) ——QQ物联·智能硬件开放平台

    平台定位 将QQ帐号体系.好友关系链.QQ消息通道及音视频服务等核心能力提供给可穿戴设备.智能家居.智能车载.传统硬件等领域的合作伙伴,实现用户与设备.设备与设备.设备与服务之间的联动. 实现用户与设 ...

  4. suse linux通过iso文件安装gcc

    mount -t iso9660 -o loop SLES-11-SP4-DVD-x86_64-GM-DVD1.iso /media/#仅仅上述iso1即可 不需要mount iso2 mount - ...

  5. 09-JavaScript高级

    今日知识 1. Dom(文档对象模型) 2. Bom(浏览器对象模型) 3. 总结 Dom 1. 获取id为div1的元素对象. * var result=document.getElementByI ...

  6. NOIP2011 D1T1 铺地毯

    P1692 铺地毯 时间: 1000ms / 空间: 131072KiB / Java类名: Main 背景 NOIP2011 day1 第一题 描述 为了准备一个独特的颁奖典礼,组织者在会场的一片矩 ...

  7. C#控制台显示进度条

    using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Prog ...

  8. Centos7中 文件大小排序

    centos7中根据文件大小排序以及jenkins配置每周删除一次jobs日志信息 https://blog.csdn.net/u013066244/article/details/70232050

  9. angular中的ng-click指令案例

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  10. 生物信息之ME, HMM, MEMM, CRF

    原文链接:http://bbs.sciencenet.cn/home.php?mod=space&uid=260809&do=blog&id=573755 注:有少量修改!如有 ...