Перейти до вмісту
Пошук в
  • Детальніше...
Шукати результати, які ...
Шукати результати в ...

[Решено] Загрузки - Неправильный тип файла!


Recommended Posts

Здравствуйте. Пытаюсь загрузить rar или zip чтобы прикрепить файл к товару, но выходит ошибка Неправильный тип файла!

В настройках стандартные типы файлов не трогал. При этом, jpg грузится без проблем.

Разрешенные расширения файлов

txt
png
jpe
jpeg
jpg
gif
bmp
ico
tiff
tif
svg
svgz
zip
rar
msi
cab
mp3
qt
mov
pdf
psd
ai
eps
ps
doc
rtf
xls
ppt
odt
ods

Разрешенные Mime типы файлов

text/plain
image/png
image/jpeg
image/jpeg
image/jpeg
image/gif
image/bmp
image/vnd.microsoft.icon
image/tiff
image/tiff
image/svg+xml
image/svg+xml
application/zip
application/x-rar-compressed
application/x-msdownload
application/vnd.ms-cab-compressed
audio/mpeg
video/quicktime
video/quicktime
application/pdf
image/vnd.adobe.photoshop
application/postscript
application/postscript
application/postscript
application/msword
application/rtf
application/vnd.ms-excel
application/vnd.ms-powerpoint
application/vnd.oasis.opendocument.text
application/vnd.oasis.opendocument.spreadsheet

Надіслати
Поділитися на інших сайтах

В админке, это не пройдет

Это  типы файлов для магазина.

Делаю ИМ по продаже цфровых товаров. Где тогда необходимо прописать разрешенные типы файлов?

post-17879-0-01311900-1426247552_thumb.jpg

post-17879-0-43671400-1426247608_thumb.jpg

 

На /download/ права 777

jpg то загружается, а zip и rar ни в какую

 

upd. Попробовал mp3, даже он загружается, а архивы игнорирует. Очень странно

upd2. Никаких сторонних модулей не устанавливалось. Всё по умолчанию

Надіслати
Поділитися на інших сайтах

ocStore 1.5.5.1.2

Вот функция загрузки /admin/controller/catalog/download.php

    public function upload() {
        $this->language->load('sale/order');
        
        $json = array();
        
        if (!$this->user->hasPermission('modify', 'catalog/download')) {
              $json['error'] = $this->language->get('error_permission');
        }    
        
        if (!isset($json['error'])) {    
            if (!empty($this->request->files['file']['name'])) {
                $filename = basename(html_entity_decode($this->request->files['file']['name'], ENT_QUOTES, 'UTF-8'));
                
                if ((utf8_strlen($filename) < 3) || (utf8_strlen($filename) > 128)) {
                    $json['error'] = $this->language->get('error_filename');
                }          
                
                // Allowed file extension types
                $allowed = array();
                
                $filetypes = explode("\n", $this->config->get('config_file_extension_allowed'));
                
                foreach ($filetypes as $filetype) {
                    $allowed[] = trim($filetype);
                }
                
                if (!in_array(substr(strrchr($filename, '.'), 1), $allowed)) {
                    $json['error'] = $this->language->get('error_filetype');
                }    
                
                // Allowed file mime types        
                $allowed = array();
                
                $filetypes = explode("\n", $this->config->get('config_file_mime_allowed'));
                
                foreach ($filetypes as $filetype) {
                    $allowed[] = trim($filetype);
                }
                                
                if (!in_array($this->request->files['file']['type'], $allowed)) {
                    $json['error'] = $this->language->get('error_filetype');
                }
                            
                if ($this->request->files['file']['error'] != UPLOAD_ERR_OK) {
                    $json['error'] = $this->language->get('error_upload_' . $this->request->files['file']['error']);
                }
                                    
                if ($this->request->files['file']['error'] != UPLOAD_ERR_OK) {
                    $json['error'] = $this->language->get('error_upload_' . $this->request->files['file']['error']);
                }
            } else {
                $json['error'] = $this->language->get('error_upload');
            }
        }
        
        if (!isset($json['error'])) {
            if (is_uploaded_file($this->request->files['file']['tmp_name']) && file_exists($this->request->files['file']['tmp_name'])) {
                $ext = md5(mt_rand());
                
                $json['filename'] = $filename . '.' . $ext;
                $json['mask'] = $filename;
                
                move_uploaded_file($this->request->files['file']['tmp_name'], DIR_DOWNLOAD . $filename . '.' . $ext);
            }
                        
            $json['success'] = $this->language->get('text_upload');
        }    
    
        $this->response->setOutput(json_encode($json));
    }
Надіслати
Поділитися на інших сайтах

Проблему решил заменив функцию upload на код, взятый из opencart 1.5.4 ))

public function upload() {
$this->language->load('sale/order');

$json = array();

if (!empty($this->request->files['file']['name'])) {
$filename = basename(html_entity_decode($this->request->files['file']['name'], ENT_QUOTES, 'UTF-8'));

if ((utf8_strlen($filename) < 3) || (utf8_strlen($filename) > 128)) {
$json['error'] = $this->language->get('error_filename');
}

if ($this->request->files['file']['error'] != UPLOAD_ERR_OK) {
$json['error'] = $this->language->get('error_upload_' . $this->request->files['file']['error']);
}
} else {
$json['error'] = $this->language->get('error_upload');
}

if (!isset($json['error'])) {
if (is_uploaded_file($this->request->files['file']['tmp_name']) && file_exists($this->request->files['file']['tmp_name'])) {
$ext = md5(mt_rand());

$json['filename'] = $filename . '.' . $ext;
$json['mask'] = $filename;

move_uploaded_file($this->request->files['file']['tmp_name'], DIR_DOWNLOAD . $filename . '.' . $ext);
}

$json['success'] = $this->language->get('text_upload');
}

$this->response->setOutput(json_encode($json));
}
Надіслати
Поділитися на інших сайтах

В код может не надо было лезть. В версии 1.5.4 уязвимость с этим http://domenam.ru/news/uyazvimost-v-opencart.html

В настройках Сервера Разрешенные Mime типы файлов:  есть запись application/zip ?

Странно конечно, почему-то движок считает что все загружаемые файлы он должен непременно уметь открывать и использовать. И на все типы файлов должны быть у него прикладные программы. 

https://ru.wikipedia.org/wiki/%D1%EF%E8%F1%EE%EA_MIME-%F2%E8%EF%EE%E2

Надіслати
Поділитися на інших сайтах


Думаю, не всё так страшно. Я не думаю, что у популярного хостинг провайдера Timeweb есть ограничения на загрузку zip и rar файлов )) В других CMS всё без проблем грузилось

Змінено користувачем efremovxp
Надіслати
Поділитися на інших сайтах

  • 2 months later...

*.docx,*.xlsx - не загружаются.

*.doc,*.xls - грузятся

OC 2.0.1.1

 

 

UP

Добавил MIME types в Настройки,Магазин,Сервер:

application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
application/vnd.openxmlformats-officedocument.wordprocessingml.document

типы брал с sitepoint.com

Змінено користувачем arshanskiyav
  • +1 1
Надіслати
Поділитися на інших сайтах


  • 2 months later...

Здраствуйте, Zip архивы не добавляются..

Способ:

Добавил MIME types в Настройки,Магазин,Сервер:
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
application/vnd.openxmlformats-officedocument.wordprocessingml.document

Не помогло, помогите пожалуйста решить проблему..

Надіслати
Поділитися на інших сайтах


Добавьте

application/x-zip-compressed
Надіслати
Поділитися на інших сайтах

Вот у меня выглядит разрешенные Mime типы файлов:

 

text/plain
image/png
image/jpeg
image/jpeg
image/jpeg
image/gif
image/bmp
image/vnd.microsoft.icon
image/tiff
image/tiff
image/svg+xml
image/svg+xml
application/x-rar-compressed
application/x-msdownload
application/vnd.ms-cab-compressed
audio/mpeg
video/quicktime
video/quicktime
application/pdf
image/vnd.adobe.photoshop
application/postscript
application/postscript
application/postscript
application/msword
application/rtf
application/vnd.ms-excel
application/vnd.ms-powerpoint
application/vnd.oasis.opendocument.text
application/vnd.oasis.opendocument.spreadsheet
application/zip
application/x-zip
application/zip-compressed
application/x-zip-compressed
application/x-compressapplication/x-rar-compressed

И всё равно не работает!

Змінено користувачем sweb27
Надіслати
Поділитися на інших сайтах


Ну... если не проходит, то выведите причину - типа тип такого-то нет в списке

 

                if (!in_array($this->request->files['file']['type'], $allowed)) {
                    $json['error'] = $this->language->get('error_filetype') . $this->request->files['file']['type'];
                }

Змінено користувачем chukcha
Надіслати
Поділитися на інших сайтах

Ну... если не проходит, то выведите причину - типа тип такого-то нет в списке

 

                if (!in_array($this->request->files['file']['type'], $allowed)) {

                    $json['error'] = $this->language->get('error_filetype') . $this->request->files['file']['type'];

                }

Подскажите пожалуйста куда это вставлять?

Просто я не очень опытен..

Надіслати
Поділитися на інших сайтах


Так что  с этим делать то?

Проверил на локальном сервере, та же проблема.

На др. хостинге, так же..

Ставил старые движки, все работает..

 

Неужели у кого то с этой версией движка работает?

Надіслати
Поділитися на інших сайтах


  • 2 weeks later...

Так что  с этим делать то?

Проверил на локальном сервере, та же проблема.

На др. хостинге, так же..

Ставил старые движки, все работает..

 

Неужели у кого то с этой версией движка работает?

Проблему решил заменив функцию upload на код, взятый из opencart 1.5.4 ))

public function upload() {
$this->language->load('sale/order');

$json = array();

if (!empty($this->request->files['file']['name'])) {
$filename = basename(html_entity_decode($this->request->files['file']['name'], ENT_QUOTES, 'UTF-8'));

if ((utf8_strlen($filename) < 3) || (utf8_strlen($filename) > 128)) {
$json['error'] = $this->language->get('error_filename');
}

if ($this->request->files['file']['error'] != UPLOAD_ERR_OK) {
$json['error'] = $this->language->get('error_upload_' . $this->request->files['file']['error']);
}
} else {
$json['error'] = $this->language->get('error_upload');
}

if (!isset($json['error'])) {
if (is_uploaded_file($this->request->files['file']['tmp_name']) && file_exists($this->request->files['file']['tmp_name'])) {
$ext = md5(mt_rand());

$json['filename'] = $filename . '.' . $ext;
$json['mask'] = $filename;

move_uploaded_file($this->request->files['file']['tmp_name'], DIR_DOWNLOAD . $filename . '.' . $ext);
}

$json['success'] = $this->language->get('text_upload');
}

$this->response->setOutput(json_encode($json));
}

Надіслати
Поділитися на інших сайтах

  • 3 weeks later...

 

Так что  с этим делать то?

Проверил на локальном сервере, та же проблема.

На др. хостинге, так же..

Ставил старые движки, все работает..

 

Неужели у кого то с этой версией движка работает?

Проблему решил заменив функцию upload на код, взятый из opencart 1.5.4 ))

public function upload() {
$this->language->load('sale/order');

$json = array();

if (!empty($this->request->files['file']['name'])) {
$filename = basename(html_entity_decode($this->request->files['file']['name'], ENT_QUOTES, 'UTF-8'));

if ((utf8_strlen($filename) < 3) || (utf8_strlen($filename) > 128)) {
$json['error'] = $this->language->get('error_filename');
}

if ($this->request->files['file']['error'] != UPLOAD_ERR_OK) {
$json['error'] = $this->language->get('error_upload_' . $this->request->files['file']['error']);
}
} else {
$json['error'] = $this->language->get('error_upload');
}

if (!isset($json['error'])) {
if (is_uploaded_file($this->request->files['file']['tmp_name']) && file_exists($this->request->files['file']['tmp_name'])) {
$ext = md5(mt_rand());

$json['filename'] = $filename . '.' . $ext;
$json['mask'] = $filename;

move_uploaded_file($this->request->files['file']['tmp_name'], DIR_DOWNLOAD . $filename . '.' . $ext);
}

$json['success'] = $this->language->get('text_upload');
}

$this->response->setOutput(json_encode($json));
}

 

 

Спасибо, подскажите пожалуйста, в каком файле менять эту функцию?

Надіслати
Поділитися на інших сайтах


Спасибо, подскажите пожалуйста, в каком файле менять эту функцию?

/admin/controller/catalog/download.php

Если не сможете разобраться, напишите в ЛС ваши данные FTP. Змінено користувачем efremovxp
Надіслати
Поділитися на інших сайтах

efremovxp

Вроде получилось, заработало, буду тестировать, если что, напишу..

Спасибо за помощь, очень выручил.

Змінено користувачем sweb27
Надіслати
Поділитися на інших сайтах


  • 1 year later...

Аналогичная проблема, версия движка OpencartPro Версия 2.1.0.2.1

Только стоит ещё модуль"Файлы для скачивания ПЛЮС"

 

Некоторые zip архивы норм закачивает а некоторые ни в какую не хочет. При этом вес у них почти идентичный.

Надіслати
Поділитися на інших сайтах


уже советовали, выведите тип файла в сообщение об ошибке

// Allowed file extension types
				$allowed = array();

				$extension_allowed = preg_replace('~\r?\n~', "\n", $this->config->get('config_file_ext_allowed'));

				$filetypes = explode("\n", $extension_allowed);

				foreach ($filetypes as $filetype) {
					$allowed[] = trim($filetype);
				}

				if (!in_array(strtolower(substr(strrchr($filename, '.'), 1)), $allowed)) {
					$json['error'] = $this->language->get('error_filetype') . strtolower(substr(strrchr($filename, '.'), 1));
				}

				// Allowed file mime types
				$allowed = array();

				$mime_allowed = preg_replace('~\r?\n~', "\n", $this->config->get('config_file_mime_allowed'));

				$filetypes = explode("\n", $mime_allowed);

				foreach ($filetypes as $filetype) {
					$allowed[] = trim($filetype);
				}

				if (!in_array($this->request->files['file']['type'], $allowed)) {
					$json['error'] = $this->language->get('error_filetype') . $this->request->files['file']['type'] ;
				}

файл /admin/controller/catalog/download.php

Надіслати
Поділитися на інших сайтах


Створіть аккаунт або увійдіть для коментування

Ви повинні бути користувачем, щоб залишити коментар

Створити обліковий запис

Зареєструйтеся для отримання облікового запису. Це просто!

Зареєструвати аккаунт

Вхід

Уже зареєстровані? Увійдіть тут.

Вхід зараз
  • Зараз на сторінці   0 користувачів

    • Ні користувачів, які переглядиють цю сторінку

×
×
  • Створити...

Important Information

На нашому сайті використовуються файли cookie і відбувається обробка деяких персональних даних користувачів, щоб поліпшити користувальницький інтерфейс. Щоб дізнатися для чого і які персональні дані ми обробляємо перейдіть за посиланням . Якщо Ви натиснете «Я даю згоду», це означає, що Ви розумієте і приймаєте всі умови, зазначені в цьому Повідомленні про конфіденційність.