1,magento前台使用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与上传时间设置了文的存储名称: 1 $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文件转数据也比较省事 (责任编辑:最模板) |