Skip to content
Advertisement

How to convert an image from input to json, send it in fetch to php and then send it on server via PHPMailer?

I’m not very good in PHP and all server stuff, so I would appreciate any answers and advice.

I need to send JSON data and an image in one fetch to php script.

Following this question How can I serialize an input File object to JSON?, I made object from image, put it in fetch and tried to send this object in PHPMailer as an attachment, but I’ve got this error:

JavaScript

So, my JavaScript code:

JavaScript

And here’s the mail.php code:

JavaScript

So, the question is, how can I change line with addAttachment so it all would work?

Just in case, I tried to use console.log to see what is in newObject, here’s the result: result in console

As you see, I also got an error in console.

I also tried to use myArray variable in js like that:

JavaScript

And then I tried to send myArray in fetch, but it didn’t work either.

I would be very grateful to any answers and recommendations!

Advertisement

Answer

Have a look at the source for the addAttachment method of PHPMailer. (Pasted to the end of this answer.)

You’re passing an object ($data-> jsonObject) where the method expects a string corresponding to a file path.

The solution could take many forms – you’ve got to find some way to take the submitted data and save at least a temporary file to the server before sending it as an attachment via PHPMailer.

You’re already sending the rest of the data in a Content-type: application/json format, but following some of the approaches in this answer which uses an enctype of multipart/form-data on the form could be one way.

Alternatively, you might 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 and reference THAT as the first arg to $mail->addAttachment.

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement