Im trying to Send an E-mail with an attachment, which the user can select with the <input type=file>
HTML-Tag.
My idea was to read the File out of the input with the Filereader
and get the Content and the Filename + type. With this three information i can create a new File with the Filename + type and the content. My First Question is:
Is this Method fine or is there a easier way to do it?
To My Problem/second Question:
This is my Code and everything works except writing the Content in the created File (PHP Code line 3). It creates the File to the right Path but the file is always empty, but selectedfile[0]
is not empty. i tried with (.txt, .docx, .pdf)
This is the value of selectedfile[0]
if i select a random .pdf file:
This is my HTML:
<input class="swal2-file" type="file" id=f_file>
This is my JavaScript:
async function() {
return new Promise((resolve, reject) => {
var selectedfile = null;
var email = $('#email').val();
var header = $('#header').val();
var content = $('#content').val();
var file = $('#files')[0].files[0];
if (file) {
var reader = new FileReader();
reader.readAsText(file, "UTF-8");
reader.onload = function (evt) {
resolve({
'email': email,
'header': header,
'content': content,
'selectedfile': [evt.target.result, file.name]
});
}
reader.onerror = function (evt) {
reject("error reading file");
}
}else {
resolve({
'email': email,
'header': header,
'content': content,
'selectedfile': null
});
}
});
With an Axios post i send the Data:
selectedfile = [0] filecontent, [1] filecontent
from Filereader
to my PHP-Backend.
This is my PHP:
$content = json_decode($request->getContent());
$selectedfile = $content->selectedfile;
file_put_contents("../storage/" . $selectedfile[1],$selectedfile[0]);