Вложение загруженного файла в виде вложения В PHPmailer и Jquery

Я создал веб-форму, где люди могут вводить регистрационную информацию и загружать изображение на наш сервер. Я могу получить их имя, адрес электронной почты и сообщение, но не могу понять, как получить загруженный файл. Я бы хотел, чтобы страница не перезагружалась, поэтому я использую JQuery. В основном это работает, но я не могу распознать загруженный файл в данных POST или FILES. Форма и страница процессора расположены в одном каталоге, а изображение помещается в подпапку, называемую загрузкой. Вот то, что я до сих пор, который не работает для прикрепления изображения. Я полагаю, что проблема в файле JavaScript, где я определяю var photoFile = $ (‘# submitForm #photoFile’). Val (); Как правильно объявить загруженный файл?

Вот HTML-форма:

form action="../inc/sendPhotoEmail.php" name="submitForm" id="submitForm" method="post"enctype="multipart/form-data">

<label for="submitName">Name <span class="required">*</span></label>
<input name="submitName" type="text" id="submitName" size="35" value="" />

<label for="submitEmail">Email <span class="required">*</span></label>
<input name="submitEmail" type="text" id="submitEmail" size="35" value="" />

<label  for="submitMessage">Tell us what you want fixed <span class="required">*</span></label>
<textarea name="submitMessage"  id="submitMessage" rows="10" cols="50" ></textarea>

<label for="attach_photo">Attach Your Photo<span class="required"/>*</span></label>
<input type="file" name="photoFile" id="photoFile" accept="image/*"/>

<button class="submit" name="submitFormSubmit" value="Submit">Submit</button>
<span id="image-loader"><img src="https://web-answers.ru/wp-content/uploads/2019/03/loader.gif" alt="" /></span>
</form> <!-- Form End -->

<!-- contact-warning -->
<div id="message-warning"></div>
<!-- contact-success -->
<div id="message-success">
<i class="icon-ok"></i>Your message was sent, thank you!<br />
</div>

JavaScript

jQuery(document).ready(function() {

$('form#submitForm button.submit').click(function() {

$('#image-loader').fadeIn();

var submitName = $('#submitForm #submitName').val();
var submitEmail = $('#submitForm #submitEmail').val();
var submitMessage = $('#submitForm #submitMessage').val();
var photoFile = $('#submitForm #photoFile').val();

var data = 'submitName=' + submitName + '&submitEmail=' + submitEmail +
'&submitMessage=' + submitMessage + $photoFile='+ photoFile;

$.ajax({

type: "POST",
url: "inc/sendPhotoEmail.php",
data: data,
success: function(msg) {

// Message was sent
if (msg == 'OK') {
$('#image-loader').fadeOut();
$('#message-warning').hide();
$('#submitForm').fadeOut();
$('#message-success').fadeIn();
}
// There was an error
else {
$('#image-loader').fadeOut();
$('#message-warning').html(msg);
$('#message-warning').fadeIn();
}

}

});

return false;

});

И файл PHP:

<?php

require_once('class.phpmailer.php');

$ourEmail = "repair@myemail.net";
$target_dir = "../uploads/";

if($_POST) {

$name = trim(stripslashes($_POST['submitName']));
$email = trim(stripslashes($_POST['submitEmail']));
$emailMessage = trim(stripslashes($_POST['submitMessage']));

$image_attachment = $_POST["photoFile"]; // <---- this doesn't print anything
$targetFile = $target_dir . basename($_FILES["photoFile"]["name"]);
echo "targetFile = ". $targetFile . "<br/>"; // <-- this only prionts the subdirectory

move_uploaded_file($_FILES["photoFile"]["tmp_name"],$target_dir.$_FILES["photoFile"]["name"]);

echo "Uploaded File :".$_FILES["photoFile"]["name"]. "<br/>";
$target_file = $target_dir . basename($_FILES["photoFile"]["name"]);
echo "target_file = ". $target_file . "<br/>";

$mail = new PHPMailer();                    //Create a new PHPMailer instance
$mail->isSendmail();                        // Set PHPMailer to use the sendmail transport

// Set Message
$mail->setFrom($email, $name);                          //Set who the message is to be sent from
$mail->addReplyTo("replyto@example.com", "First Last"); //Set an alternative reply-to address
$mail->addAddress($ourEmail, "Figley T. Whitesides");   //Set who the message is to be sent to
$mail->Subject = "Repair Form Submission";              //Set the subject line
$mail->WordWrap = 80;
$mail->msgHTML($emailMessage);                          //Create message bodies and embed images
$mail->addAttachment($target_file);                     //Attach an image file

if (!$error) {
//send the message, check for errors
if (!$mail->send()) {
$mail->ErrorInfo;
} else {
$response = "Photo sent!";
} // end if - no validation error
}

else{
$response = (isset($error['name'])) ? $error['name'] . "<br /> \n" : null;
$response .= (isset($error['email'])) ? $error['email'] . "<br /> \n" : null;
$response .= (isset($error['message'])) ? $error['message'] . "<br />" : null;
$response .= (isset($error['attachment'])) ? $error['attachment'] . "<br />" : null;

echo $response;
} // end if - there was a validation error
}
?>});

0

Решение

Вы не можете загружать данные и файлы с помощью одной формы, используя ajax, но попробуйте этот код,

$("form#data").submit(function() {
var formData = new FormData($(this)[0]);
$.post($(this).attr("action"), formData, function() {
// success
});
return false;
});
1

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector