PrestaShop:允许客户上传PDF,AI和EPS文件作为产品定制 [英] PrestaShop: allow customers to upload PDF, AI and EPS files as product customization

查看:458
本文介绍了PrestaShop:允许客户上传PDF,AI和EPS文件作为产品定制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行Prestashop 1.6.1.7,我有以下的pictureUpload()方法,允许用户上传自己选择的文件。默认情况下,Prestashop只允许上传GIF,JPG,JPEG或PNG。



我试图让用户能够上传更多的类型(pdf,ai和eps专门)



以下是productController覆盖中的pictureUpload()方法:

  protected function pictureUpload()
{
if(!$ field_ids = $ this-> product-> getCustomizationFieldIds()){
return false;
}
$ authorized_file_fields = array();
foreach($ field_ids as $ field_id){
if($ field_id ['type'] == Product :: CUSTOMIZE_FILE){
$ authorized_file_fields [(int)$ field_id ['id_customization_field' ]] ='file'。(int)$ field_id ['id_customization_field'];
}
}
$ indexes = array_flip($ authorized_file_fields);
foreach($ _FILES as $ field_name => $ file){
if(in_array($ field_name,$ authorized_file_fields)&& isset($ file ['tmp_name'])&& !($ file ['tmp_name'])){
// $ file_name = md5(uniqid(rand(),true));
$ file_name = $ file ['name']; // $ this
$ b $ if($ error = ImageManager :: validateUpload($ file,(int)Configuration :: get('PS_PRODUCT_PICTURE_MAX_SIZE'))){
$ this-> errors [] = $错误;

$ b $ product_picture_width =(int)配置:: get('PS_PRODUCT_PICTURE_WIDTH');
$ product_picture_height =(int)配置:: get('PS_PRODUCT_PICTURE_HEIGHT');
$ tmp_name = tempnam(_PS_TMP_IMG_DIR_,'PS');
if($ error ||(!$ tmp_name ||!move_uploaded_file($ file ['tmp_name'],$ tmp_name))){
return false;

原始文件* /
if(!ImageManager :: resize($ tmp_name,_PS_UPLOAD_DIR _。$ file_name)){
$ this-> errors [] =工具:: displayError('图片上传过程中发生错误');
}
* *小一个* /
elseif(!ImageManager :: resize($ tmp_name,_PS_UPLOAD_DIR _。$ file_name .__ small',$ product_picture_width,$ product_picture_height)){
$ this-> errors [] = Tools :: displayError('在图片上传过程中发生错误。
} elseif(!chmod(_PS_UPLOAD_DIR _。$ file_name,0777)||!chmod(_PS_UPLOAD_DIR _。$ file_name .__ small',0777)){
$ this-> errors [] =工具: :displayError('图片上传过程中发生错误');
} else {
$ this-> context-> cart-> addPictureToProduct($ this-> product-> id,$ indexes [$ field_name],Product :: CUSTOMIZE_FILE,$文件名);
}
unlink($ tmp_name);
}
}
返回true;



$ b $ p
$ b

这是看ImageManager类,它有这个方法(我有更新错误信息):
$ b $ pre $ public static function validateUpload($ file,$ max_file_size = 0,$ types = null)$ ((int)$ max_file_size> 0&& $ file ['size']>(int)$ max_file_size){
返回sprintf(工具)b $ b {

:: displayError('Image is too large(%1 $ d kB)。Maximum maximum:%2 $ d kB'),$ file ['size'] / 1024,$ max_file_size / 1024); $!
$ b if(!ImageManager :: isRealImage($ file ['tmp_name'],$ file ['type'])||!ImageManager :: isCorrectImageFileExt($ file ['name'],$类型)|| preg_match('/ \%00 /',$ file ['name'])){
return Tools :: displayError('Image format not recognized,allowed formats are:.gif,.jpg ,.png,.pdf,.ai,.eps'); //我更新了这个 - 这是当我尝试上传AI

时启动的错误if($ file ['error']){
return sprintf(Tools :: displayError( '上传图片时出错,请更改您的服务器的设置(错误代码:%s)'),$ file ['error']);
}
返回false;



$ b $ p
$ b

该方法失败的地方是指向下面两个额外的方法。我更新了isRealImage方法,试图让我想要的类型,但它仍然失败(我评论它失败的地方)。

  public static function isRealImage($ filename,$ file_mime_type = null,$ mime_type_list = null)
{
//检测mime内容类型
$ mime_type = false;
if(!$ mime_type_list){
//我更新了这个列表来允许其他FILETYPES
$ mime_type_list = array('image / gif','image / jpg','image / jpeg','image / pjpeg','image / png','image / x-png','application / illustrator','application / ai','application / eps','application / x-eps'图像/ eps','图像/ x-eps','application / pdf','application / acrobat','application / x-pdf','text / pdf','text / x-pdf'


//尝试4种不同的方法来确定mime类型

if(function_exists('getimagesize')){
$ image_info = @和getimagesize($文件名);
//这里的IMAGE_INFO显示为'FALSE',所以当上传一个.AI文件
时,
} else {
$ file_mime_type = false;
}
} elseif(function_exists('finfo_open')){
$ const = defined('FILEINFO_MIME_TYPE')? FILEINFO_MIME_TYPE:FILEINFO_MIME;
$ finfo = finfo_open($ const);
$ mime_type = finfo_file($ finfo,$ filename);
finfo_close($ finfo);
} elseif(function_exists('mime_content_type')){
$ mime_type = mime_content_type($ filename);
} elseif(function_exists('exec')){
$ mime_type = trim(exec('file -b --mime-type'.escapeshellarg($ filename)));
if(!$ mime_type){
$ mime_type = trim(exec('file --mime'.escapeshellarg($ filename)));

if(!$ mime_type){
$ mime_type = trim(exec('file -bi'.escapeshellarg($ filename)));


$ b $ if($ file_mime_type&&(empty($ mime_type)|| $ mime_type =='regular file'|| $ mime_type =='text / plain')){
$ mime_type = $ file_mime_type;
}

//对于每个允许的MIME类型,我们在当前的MIME类型
foreach($ mime_type_list as $ type){
if strstr($ mime_type,$ type)){
return true;
}
}

return false;
}

我还更新了isCorrectImageFileExt方法:

  public static function isCorrectImageFileExt($ filename,$ authorized_extensions = null)
{
//过滤文件扩展名
if($ authorized_extensions === null){
//已添加允许的类型我想要
$ authorized_extensions = array('gif','jpg','jpeg','jpe','png','pdf' ,ai,eps);
}
$ name_explode = explode('。',$ filename);
if(count($ name_explode)> = 2){
$ current_extension = strtolower($ name_explode [count($ name_explode) - 1]);
if(!in_array($ current_extension,$ authorized_extensions)){
return false;
}
} else {
return false;
}

return true;

$ / code>

对此有何想法?

帮助解决方案

您已经太深了:)。这是我已经完成的 ProductController pictureUpload 方法,您不需要其他覆盖。通过我的覆盖,你可以上传pdf,ai,cdr和eps,但显然你可以根据自己的需求进行更改。

  protected function pictureUpload ()
{
if(!$ field_ids = $ this-> product-> getCustomizationFieldIds()){
return false;
}
$ authorized_file_fields = array();
foreach($ field_ids as $ field_id){
if($ field_id ['type'] == Product :: CUSTOMIZE_FILE){
$ authorized_file_fields [(int)$ field_id ['id_customization_field' ]] ='file'。(int)$ field_id ['id_customization_field'];
}
}
$ indexes = array_flip($ authorized_file_fields);
$ b $ foreach($ _FILES as $ field_name => $ file){
if(in_array($ field_name,$ authorized_file_fields)&& isset($ file ['tmp_name']) &&!empty($ file ['tmp_name'])){
$ file_name = md5(uniqid(rand(),true));

//错误检查,但快速
$ extension = substr($ file ['name'],-3,3);
if($ extension =='jpg'OR $ extension =='gif'OR $ extension =='png'){
if($ error = ImageManager :: validateUpload($ file,(int )Configuration :: get('PS_PRODUCT_PICTURE_MAX_SIZE'))){
$ this-> errors [] = $ error;

$ b $ product_picture_width =(int)配置:: get('PS_PRODUCT_PICTURE_WIDTH');
$ product_picture_height =(int)配置:: get('PS_PRODUCT_PICTURE_HEIGHT');
$ tmp_name = tempnam(_PS_TMP_IMG_DIR_,'PS');
if($ error ||(!$ tmp_name ||!move_uploaded_file($ file ['tmp_name'],$ tmp_name))){
return false;

原始文件* /
if(!ImageManager :: resize($ tmp_name,_PS_UPLOAD_DIR _。$ file_name)){
$ this-> errors [] =工具:: displayError('图片上传过程中发生错误');
}
* *小一个* /
elseif(!ImageManager :: resize($ tmp_name,_PS_UPLOAD_DIR _。$ file_name .__ small',$ product_picture_width,$ product_picture_height)){
$ this-> errors [] = Tools :: displayError('在图片上传过程中发生错误。
} elseif(!chmod(_PS_UPLOAD_DIR _。$ file_name,0777)||!chmod(_PS_UPLOAD_DIR _。$ file_name .__ small',0777)){
$ this-> errors [] =工具: :displayError('图片上传过程中发生错误');
} else {
$ this-> context-> cart-> addPictureToProduct($ this-> product-> id,$ indexes [$ field_name],Product :: CUSTOMIZE_FILE,$文件名);
}
unlink($ tmp_name);
} elseif($ extension =='pdf'OR $ extension =='.ai'OR $ extension =='cdr'OR $ extension =='eps'){
$ file_name = $ file_name '。'。str_replace('。','',$ extension);
if(!move_uploaded_file($ file ['tmp_name'],_PS_UPLOAD_DIR _。$ file_name)){
return false;
}
chmod(_PS_UPLOAD_DIR _。$ file_name,0777);
$ this-> context-> cart-> addPictureToProduct($ this-> product-> id,$ indexes [$ field_name],Product :: CUSTOMIZE_FILE,$ file_name);
} else {
$ this-> errors [] = Tools :: displayError('This format is not accepted');
}
}
}
返回true;



$ b $ p
$ b

之后你必须定制 product.tpl ,模板的购物车摘要以及后台订单明细:)

I am running Prestashop 1.6.1.7 and I have the following pictureUpload() method that allows users to upload files of their choosing. By default Prestashop allows uploads of GIF, JPG, JPEG or PNG only.

I'm trying to allow users the ability to upload a few more types (pdf, ai and eps specifically)

Here is the pictureUpload() method in the productController override:

protected function pictureUpload()
{
    if (!$field_ids = $this->product->getCustomizationFieldIds()) {
        return false;
    }
    $authorized_file_fields = array();
    foreach ($field_ids as $field_id) {
        if ($field_id['type'] == Product::CUSTOMIZE_FILE) {
            $authorized_file_fields[(int)$field_id['id_customization_field']] = 'file'.(int)$field_id['id_customization_field'];
        }
    }
    $indexes = array_flip($authorized_file_fields);
    foreach ($_FILES as $field_name => $file) {
        if (in_array($field_name, $authorized_file_fields) && isset($file['tmp_name']) && !empty($file['tmp_name'])) {
            //$file_name = md5(uniqid(rand(), true));
            $file_name = $file['name']; // In this

            if ($error = ImageManager::validateUpload($file, (int)Configuration::get('PS_PRODUCT_PICTURE_MAX_SIZE'))) {
                $this->errors[] = $error;
            }

            $product_picture_width = (int)Configuration::get('PS_PRODUCT_PICTURE_WIDTH');
            $product_picture_height = (int)Configuration::get('PS_PRODUCT_PICTURE_HEIGHT');
            $tmp_name = tempnam(_PS_TMP_IMG_DIR_, 'PS');
            if ($error || (!$tmp_name || !move_uploaded_file($file['tmp_name'], $tmp_name))) {
                return false;
            }
            /* Original file */
            if (!ImageManager::resize($tmp_name, _PS_UPLOAD_DIR_.$file_name)) {
                $this->errors[] = Tools::displayError('An error occurred during the image upload process.');
            }
            /* A smaller one */
            elseif (!ImageManager::resize($tmp_name, _PS_UPLOAD_DIR_.$file_name.'_small', $product_picture_width, $product_picture_height)) {
                $this->errors[] = Tools::displayError('An error occurred during the image upload process.');
            } elseif (!chmod(_PS_UPLOAD_DIR_.$file_name, 0777) || !chmod(_PS_UPLOAD_DIR_.$file_name.'_small', 0777)) {
                $this->errors[] = Tools::displayError('An error occurred during the image upload process.');
            } else {
                $this->context->cart->addPictureToProduct($this->product->id, $indexes[$field_name], Product::CUSTOMIZE_FILE, $file_name);
            }
            unlink($tmp_name);
        }
    }
    return true;
}

This is looking to the ImageManager class, which has this method (that I have updated the error message on):

public static function validateUpload($file, $max_file_size = 0, $types = null)
{

    if ((int)$max_file_size > 0 && $file['size'] > (int)$max_file_size) {
        return sprintf(Tools::displayError('Image is too large (%1$d kB). Maximum allowed: %2$d kB'), $file['size'] / 1024, $max_file_size / 1024);
    }
    if (!ImageManager::isRealImage($file['tmp_name'], $file['type']) || !ImageManager::isCorrectImageFileExt($file['name'], $types) || preg_match('/\%00/', $file['name'])) {
        return Tools::displayError('Image format not recognized, allowed formats are: .gif, .jpg, .png, .pdf, .ai, .eps'); //I Updated This - this is the error kicking off when I try to upload AI
    }
    if ($file['error']) {
        return sprintf(Tools::displayError('Error while uploading image; please change your server\'s settings. (Error code: %s)'), $file['error']);
    }
    return false;
}

The place where that method fails is pointing to two additional methods posted below. I updated the isRealImage method to try and allow the types I wanted through, but it still fails (and I commented where it fails).

public static function isRealImage($filename, $file_mime_type = null, $mime_type_list = null)
{
    // Detect mime content type
    $mime_type = false;
    if (!$mime_type_list) {
        //I UPDATED THIS LIST TO ALLOW FOR OTHER FILETYPES
        $mime_type_list = array('image/gif', 'image/jpg', 'image/jpeg', 'image/pjpeg', 'image/png', 'image/x-png', 'application/illustrator', 'application/ai', 'application/eps', 'application/x-eps', 'image/eps', 'image/x-eps', 'application/pdf', 'application/acrobat', 'application/x-pdf', 'text/pdf', 'text/x-pdf');
    }

    // Try 4 different methods to determine the mime type

    if (function_exists('getimagesize')) {
        $image_info = @getimagesize($filename);
        //HERE IMAGE_INFO IS SHOWING AS 'FALSE' SO IT GOES NO FURTHER WHEN UPLOADING A .AI FILE
        if ($image_info) {
            $mime_type = $image_info['mime'];
        } else {
            $file_mime_type = false;
        }
    } elseif (function_exists('finfo_open')) {
        $const = defined('FILEINFO_MIME_TYPE') ? FILEINFO_MIME_TYPE : FILEINFO_MIME;
        $finfo = finfo_open($const);
        $mime_type = finfo_file($finfo, $filename);
        finfo_close($finfo);
    } elseif (function_exists('mime_content_type')) {
        $mime_type = mime_content_type($filename);
    } elseif (function_exists('exec')) {
        $mime_type = trim(exec('file -b --mime-type '.escapeshellarg($filename)));
        if (!$mime_type) {
            $mime_type = trim(exec('file --mime '.escapeshellarg($filename)));
        }
        if (!$mime_type) {
            $mime_type = trim(exec('file -bi '.escapeshellarg($filename)));
        }
    }

    if ($file_mime_type && (empty($mime_type) || $mime_type == 'regular file' || $mime_type == 'text/plain')) {
        $mime_type = $file_mime_type;
    }

    // For each allowed MIME type, we are looking for it inside the current MIME type
    foreach ($mime_type_list as $type) {
        if (strstr($mime_type, $type)) {
            return true;
        }
    }

    return false;
}

I also updated the isCorrectImageFileExt method:

public static function isCorrectImageFileExt($filename, $authorized_extensions = null)
{
    // Filter on file extension
    if ($authorized_extensions === null) {
        //ADDED ALLOWED TYPES I WANT
        $authorized_extensions = array('gif', 'jpg', 'jpeg', 'jpe', 'png', 'pdf', 'ai', 'eps');
    }
    $name_explode = explode('.', $filename);
    if (count($name_explode) >= 2) {
        $current_extension = strtolower($name_explode[count($name_explode) - 1]);
        if (!in_array($current_extension, $authorized_extensions)) {
            return false;
        }
    } else {
        return false;
    }

    return true;
}

Thoughts on this?

Help on this?

解决方案

You have gone too deep :). This is the pictureUpload method of ProductController that I've already made, you don't need others overrides. With my override you can upload pdf, ai, cdr and eps, but obviously you can change with your needs.

protected function pictureUpload()
{
    if (!$field_ids = $this->product->getCustomizationFieldIds()) {
        return false;
    }
    $authorized_file_fields = array();
    foreach ($field_ids as $field_id) {
        if ($field_id['type'] == Product::CUSTOMIZE_FILE) {
            $authorized_file_fields[(int)$field_id['id_customization_field']] = 'file'.(int)$field_id['id_customization_field'];
        }
    }
    $indexes = array_flip($authorized_file_fields);

    foreach ($_FILES as $field_name => $file) {
        if (in_array($field_name, $authorized_file_fields) && isset($file['tmp_name']) && !empty($file['tmp_name'])) {
            $file_name = md5(uniqid(rand(), true));

            // Bad check, but rapid
            $extension = substr($file['name'], -3, 3);
            if($extension == 'jpg' OR $extension == 'gif' OR $extension == 'png'){
                if ($error = ImageManager::validateUpload($file, (int)Configuration::get('PS_PRODUCT_PICTURE_MAX_SIZE'))) {
                    $this->errors[] = $error;
                }

                $product_picture_width = (int)Configuration::get('PS_PRODUCT_PICTURE_WIDTH');
                $product_picture_height = (int)Configuration::get('PS_PRODUCT_PICTURE_HEIGHT');
                $tmp_name = tempnam(_PS_TMP_IMG_DIR_, 'PS');
                if ($error || (!$tmp_name || !move_uploaded_file($file['tmp_name'], $tmp_name))) {
                    return false;
                }
                /* Original file */
                if (!ImageManager::resize($tmp_name, _PS_UPLOAD_DIR_.$file_name)) {
                    $this->errors[] = Tools::displayError('An error occurred during the image upload process.');
                }
                /* A smaller one */
                elseif (!ImageManager::resize($tmp_name, _PS_UPLOAD_DIR_.$file_name.'_small', $product_picture_width, $product_picture_height)) {
                    $this->errors[] = Tools::displayError('An error occurred during the image upload process.');
                } elseif (!chmod(_PS_UPLOAD_DIR_.$file_name, 0777) || !chmod(_PS_UPLOAD_DIR_.$file_name.'_small', 0777)) {
                    $this->errors[] = Tools::displayError('An error occurred during the image upload process.');
                } else {
                    $this->context->cart->addPictureToProduct($this->product->id, $indexes[$field_name], Product::CUSTOMIZE_FILE, $file_name);
                }
                unlink($tmp_name);
            } elseif ($extension == 'pdf' OR $extension == '.ai' OR $extension == 'cdr' OR $extension == 'eps') {
                $file_name = $file_name.'.'.str_replace('.', '', $extension);
                if (!move_uploaded_file($file['tmp_name'], _PS_UPLOAD_DIR_.$file_name)) {
                    return false;
                }
                chmod(_PS_UPLOAD_DIR_.$file_name, 0777);
                $this->context->cart->addPictureToProduct($this->product->id, $indexes[$field_name], Product::CUSTOMIZE_FILE, $file_name);
            } else {
                $this->errors[] = Tools::displayError('This format is not accepted');
            }
        }
    }
    return true;
}

After that you have to customize product.tpl, the cart summary of your template, and the backoffice order detail :)

这篇关于PrestaShop:允许客户上传PDF,AI和EPS文件作为产品定制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆