如何将图像从输入转换为 json,将其发送到 php,然后通过 PHPMailer 将其发送到服务器?
How to convert an image from input to json, send it in fetch to php and then send it on server via PHPMailer?
我在 PHP 和所有服务器方面不是很好,所以我将不胜感激任何答案和建议。
我需要将 JSON 数据和图像一次性发送到 php 脚本。
根据这个问题 How can I serialize an input File object to JSON?,我从图像中创建了对象,将其放入 fetch 中并尝试将此对象作为附件发送到 PHPMailer,但我遇到了这个错误:
[Sun Jan 24 15:07:52 2021] 127.0.0.1:59260 [500]: POST /dist/php/mail.php - Uncaught Error: Object of class stdClass could not be converted to string in /home/joe/Documents/vscode-projects/html-projects/swipeskins/dist/vendor/phpmailer/phpmailer/src/PHPMailer.php:3005
所以,我的 JavaScript 代码:
// firstly, declaration of variables
let files,
fileObject,
newObject,
myArray = [];
// when user uploads image with input, code makes new src for <img> tag with this image
form.onchange = (event) => {
image.src = URL.createObjectURL(event.target.files[0]);
image.onload = () => {
// on load of image I give new values to variables, and make an object with info from an image
files = document.querySelector('[type=file]').files;
fileObject = files[0];
newObject = {
'lastModified' : fileObject.lastModified,
'lastModifiedDate' : fileObject.lastModifiedDate,
'name' : fileObject.name,
'size' : fileObject.size,
'type' : fileObject.type
};
}
}
// And here's the fetch :)
fetch(`${server}/dist/php/mail.php`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
'preferences': purchase, // this is usual object
'jsonObject': newObject, // and this is an image object
})
});
这里是 mail.php 代码:
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: *');
header('Access-Control-Allow-Methods: *');
header('Content-Type: application/json');
require_once "../vendor/autoload.php";
$data = json_decode(file_get_contents('php://input'));
send_mail('pansfloyd@gmail.com', 'joe brock', $data);
function send_mail($email, $name, $data) {
$mail = new PHPMailer(true);
$mail->SMTPDebug = 3;
$mail->isSMTP();
$mail->Host = "smtp.gmail.com";
$mail->SMTPAuth = true;
$mail->Username = "dealinmaivasha@gmail.com";
$mail->Password = "password"; //changed this :D
$mail->SMTPSecure = "tls";
$mail->Port = 587;
$mail->From = "dealinmaivasha@gmail.com";
$mail->FromName = "Dealin Maivasha";
$mail->addAddress($email, $name);
$mail->isHTML(true);
$mail->Subject = "Subject Text";
$mail->addAttachment($data->jsonObject); // SO, this is where I need to send image, and this line doesn't work at all
$mail->Body = "Body";
$mail->AltBody = "This is the plain text version of the email content";
try {
$mail->send();
echo "Message has been sent successfully";
} catch (Exception $e) {
echo "Mailer Error: " . $mail->ErrorInfo;
}
}
所以,问题是,我怎样才能用 addAttachment 改变行,这样一切都会起作用?
为了以防万一,我尝试使用 console.log 查看 newObject 中的内容,结果如下:
result in console
如你所见,我在控制台中也遇到了错误。
我也试过在 js 中使用 myArray 变量:
myArray.push(newObject)
然后我尝试在 fetch 中发送 myArray,但它也没有用。
如果有任何答案和建议,我将不胜感激!
看看the source for the addAttachment
method of PHPMailer
。 (粘贴到此答案的末尾。)
您正在传递一个对象 ($data-> jsonObject
),其中该方法需要一个对应于文件路径的字符串。
解决方案可以采用多种形式 - 您必须找到一些方法来获取提交的数据并至少将一个临时文件保存到服务器,然后再通过 PHPMailer 将其作为附件发送。
您已经以 Content-type: application/json
格式发送其余数据,但遵循 中的一些方法,其中使用 enctype
的 multipart/form-data
在表格上可能是一种方式。
或者,您可以 convert the image's data to base64 and POST it with the rest of your JSON data. Then, on the other side, decode & save to /tmp/{filename}.ext
并将 THAT 作为 $mail->addAttachment
的第一个参数引用。
/**
* Add an attachment from a path on the filesystem.
* Never use a user-supplied path to a file!
* Returns false if the file could not be found or read.
* Explicitly *does not* support passing URLs; PHPMailer is not an HTTP client.
* If you need to do that, fetch the resource yourself and pass it in via a local file or string.
*
* @param string $path Path to the attachment
* @param string $name Overrides the attachment name
* @param string $encoding File encoding (see $Encoding)
* @param string $type MIME type, e.g. `image/jpeg`; determined automatically from $path if not specified
* @param string $disposition Disposition to use
*
* @throws Exception
*
* @return bool
*/
public function addAttachment(
$path,
$name = '',
$encoding = self::ENCODING_BASE64,
$type = '',
$disposition = 'attachment'
) {
...
}
我在 PHP 和所有服务器方面不是很好,所以我将不胜感激任何答案和建议。
我需要将 JSON 数据和图像一次性发送到 php 脚本。
根据这个问题 How can I serialize an input File object to JSON?,我从图像中创建了对象,将其放入 fetch 中并尝试将此对象作为附件发送到 PHPMailer,但我遇到了这个错误:
[Sun Jan 24 15:07:52 2021] 127.0.0.1:59260 [500]: POST /dist/php/mail.php - Uncaught Error: Object of class stdClass could not be converted to string in /home/joe/Documents/vscode-projects/html-projects/swipeskins/dist/vendor/phpmailer/phpmailer/src/PHPMailer.php:3005
所以,我的 JavaScript 代码:
// firstly, declaration of variables
let files,
fileObject,
newObject,
myArray = [];
// when user uploads image with input, code makes new src for <img> tag with this image
form.onchange = (event) => {
image.src = URL.createObjectURL(event.target.files[0]);
image.onload = () => {
// on load of image I give new values to variables, and make an object with info from an image
files = document.querySelector('[type=file]').files;
fileObject = files[0];
newObject = {
'lastModified' : fileObject.lastModified,
'lastModifiedDate' : fileObject.lastModifiedDate,
'name' : fileObject.name,
'size' : fileObject.size,
'type' : fileObject.type
};
}
}
// And here's the fetch :)
fetch(`${server}/dist/php/mail.php`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
'preferences': purchase, // this is usual object
'jsonObject': newObject, // and this is an image object
})
});
这里是 mail.php 代码:
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: *');
header('Access-Control-Allow-Methods: *');
header('Content-Type: application/json');
require_once "../vendor/autoload.php";
$data = json_decode(file_get_contents('php://input'));
send_mail('pansfloyd@gmail.com', 'joe brock', $data);
function send_mail($email, $name, $data) {
$mail = new PHPMailer(true);
$mail->SMTPDebug = 3;
$mail->isSMTP();
$mail->Host = "smtp.gmail.com";
$mail->SMTPAuth = true;
$mail->Username = "dealinmaivasha@gmail.com";
$mail->Password = "password"; //changed this :D
$mail->SMTPSecure = "tls";
$mail->Port = 587;
$mail->From = "dealinmaivasha@gmail.com";
$mail->FromName = "Dealin Maivasha";
$mail->addAddress($email, $name);
$mail->isHTML(true);
$mail->Subject = "Subject Text";
$mail->addAttachment($data->jsonObject); // SO, this is where I need to send image, and this line doesn't work at all
$mail->Body = "Body";
$mail->AltBody = "This is the plain text version of the email content";
try {
$mail->send();
echo "Message has been sent successfully";
} catch (Exception $e) {
echo "Mailer Error: " . $mail->ErrorInfo;
}
}
所以,问题是,我怎样才能用 addAttachment 改变行,这样一切都会起作用?
为了以防万一,我尝试使用 console.log 查看 newObject 中的内容,结果如下: result in console
如你所见,我在控制台中也遇到了错误。
我也试过在 js 中使用 myArray 变量:
myArray.push(newObject)
然后我尝试在 fetch 中发送 myArray,但它也没有用。
如果有任何答案和建议,我将不胜感激!
看看the source for the addAttachment
method of PHPMailer
。 (粘贴到此答案的末尾。)
您正在传递一个对象 ($data-> jsonObject
),其中该方法需要一个对应于文件路径的字符串。
解决方案可以采用多种形式 - 您必须找到一些方法来获取提交的数据并至少将一个临时文件保存到服务器,然后再通过 PHPMailer 将其作为附件发送。
您已经以 Content-type: application/json
格式发送其余数据,但遵循 enctype
的 multipart/form-data
在表格上可能是一种方式。
或者,您可以 convert the image's data to base64 and POST it with the rest of your JSON data. Then, on the other side, decode & save to /tmp/{filename}.ext
并将 THAT 作为 $mail->addAttachment
的第一个参数引用。
/**
* Add an attachment from a path on the filesystem.
* Never use a user-supplied path to a file!
* Returns false if the file could not be found or read.
* Explicitly *does not* support passing URLs; PHPMailer is not an HTTP client.
* If you need to do that, fetch the resource yourself and pass it in via a local file or string.
*
* @param string $path Path to the attachment
* @param string $name Overrides the attachment name
* @param string $encoding File encoding (see $Encoding)
* @param string $type MIME type, e.g. `image/jpeg`; determined automatically from $path if not specified
* @param string $disposition Disposition to use
*
* @throws Exception
*
* @return bool
*/
public function addAttachment(
$path,
$name = '',
$encoding = self::ENCODING_BASE64,
$type = '',
$disposition = 'attachment'
) {
...
}