@panterr92

Как правильно передавать файл в контроллер в OpenCart 2.3?

Добрый день, не получается передать файл через форму и FormData
Сейчас код в текущем состоянии:

<form id="selection-form" method="post" name="fileinfo">
	<input type="file" name="file" value="" /> 
	<input type="number" name="selection_mu">
	<input type="number" name="selection_dp">
	<input type="number" name="selection_bs">
	<input type="number" name="selection_dk">
	<input type="text" id="phone" name="selection_phone">
	<input type="submit"  id="selection-send" value="Отправить специалисту">
</form>


var form = document.forms.namedItem("fileinfo");
form.addEventListener('submit', function(ev) {

	var oOutput = document.querySelector("div"),
		oData = new FormData(form);

	oData.append("CustomField", "This is some extra data");

	var oReq = new XMLHttpRequest();
	
	oReq.open("POST", "index.php?route=information/information/send", true);
	oReq.onload = function(oEvent) {
	
		if (oReq.status == 200) {
			console.log('Uploaded!');
			console.log(oReq.response);
            console.log(oReq.responseText);
		} else {
			console.log("Error " + oReq.status + " occurred when trying to upload your file.<br \/>");
		}
	};

	oReq.send(oData);
	ev.preventDefault();
}, false);


контроллер
public function send() {
		
		$json = array();
		
		if ($this->request->server['REQUEST_METHOD'] == 'POST') {
			
			$message = '';
			
			if (isset($this->request->post['selection_mu'])) {
				$message .= $this->request->post['selection_mu'].'<br>';
			}
			
			if (isset($this->request->post['selection_dp'])) {
				$message .= $this->request->post['selection_dp'].'<br>';
			}
			
			if (isset($this->request->post['selection_bs'])) {
				$message .= $this->request->post['selection_bs'].'<br>';
			}
			
			if (isset($this->request->post['selection_dk'])){
				$message .= $this->request->post['selection_dk'].'<br>';
			}
			
			if (isset($this->request->post['selection_phone'])) {
				$message .= $this->request->post['selection_phone'].'</b><br>';
			}
			
			$mail = new Mail();
			$mail->protocol = $this->config->get('config_mail_protocol');
			$mail->parameter = $this->config->get('config_mail_parameter');
			$mail->smtp_hostname = $this->config->get('config_mail_smtp_hostname');
			$mail->smtp_username = $this->config->get('config_mail_smtp_username');
			$mail->smtp_password = html_entity_decode($this->config->get('config_mail_smtp_password'), ENT_QUOTES, 'UTF-8');
			$mail->smtp_port = $this->config->get('config_mail_smtp_port');
			$mail->smtp_timeout = $this->config->get('config_mail_smtp_timeout');

			$mail->setTo('admin@admin.ru');
			$mail->setFrom('no-reply@admin.ru');
			$mail->setSender(html_entity_decode('Подбор замка по фото', ENT_QUOTES, 'UTF-8'));
			$mail->setSubject('Сообщение');
			$mail->setText($message);
			
			// Подгружаем файлы
			if (isset($this->request->post['file'])){
                $mail->addAttachment(DIR_UPLOAD.$this->request->post['file']);
				$json['file'] = $this->request->post['file'];
            }
			
			$mail->send();
			$json['success'] = $this->request->post['file'];
			
			$this->response->addHeader('Content-Type: application/json');
			$this->response->setOutput(json_encode($json));
		}
	}


Если начинать дебажить, то $this->request->post['file'] undefinded
  • Вопрос задан
  • 1127 просмотров
Пригласить эксперта
Ответы на вопрос 1
@amfetamine
В исходниках все давным-давно реализовано
$('button[id^=\'button-upload\']').on('click', function() {
	var node = this;

	$('#form-upload').remove();

	$('body').prepend('<form enctype="multipart/form-data" id="form-upload" style="display: none;"><input type="file" name="file" /></form>');

	$('#form-upload input[name=\'file\']').trigger('click');

	if (typeof timer != 'undefined') {
    	clearInterval(timer);
	}

	timer = setInterval(function() {
		if ($('#form-upload input[name=\'file\']').val() != '') {
			clearInterval(timer);

			$.ajax({
				url: 'index.php?route=tool/upload',
				type: 'post',
				dataType: 'json',
				data: new FormData($('#form-upload')[0]),
				cache: false,
				contentType: false,
				processData: false,
				beforeSend: function() {
					$(node).button('loading');
				},
				complete: function() {
					$(node).button('reset');
				},
				success: function(json) {
					$('.text-danger').remove();

					if (json['error']) {
						$(node).parent().find('input').after('<div class="text-danger">' + json['error'] + '</div>');
					}

					if (json['success']) {
						alert(json['success']);

						$(node).parent().find('input').val(json['code']);
					}
				},
				error: function(xhr, ajaxOptions, thrownError) {
					alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
				}
			});
		}
	}, 500);
});
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы