I currently have a traditional html email form sending a post request with a file the user can upload. I want to be able to flash a success message once the email is sent, and in order to do that I need to either use ajax or make the post request using express - and not rely on the traditional html form submission.
How do I send a file (not the filepath string) to the server? Currently I'm assigning the input element an ID and and grabbing its value. However this grabs the string of the file path to the file, and does not send the actual file.
Client
<form enctype="multipart/form-data">
<input type="text" name="name" class="form-control" id="name">
<!--code below uploads file -->
<input type="file"
style="visibility:hidden; width: 1px;"
id='${multipartFilePath}' class="res" name='userFile' onchange="$(this).parent().find('span').html($(this).val().replace('C:\\fakepath\\', ''))" /> <!-- Chrome security returns 'C:\fakepath\' -->
<input class="btn btn-default btn-file" type="button" value="Attach File" onclick="$(this).parent().find('input[type=file]').click();"/>
</form>
<button type="submit" class="btn btn-xl sub">Send Message</button>
<script type="text/javascript">
$(".sub").click(function() {
alert("submitted");
var name, email, phone, message, resume;
name = $("#name").val();
email = $("#email").val();
phone = $("#phone").val();
message = $("#message").val();
resume = $(".res").val();
alert(resume);//Prints out file path
$("#flash").text("Sending E-mail...Please wait");
$.post("/email", {
name: name,
email: email,
phone: phone,
message: message,
resume: resume
}, function(data) {
if (data == "sent") {
$("#flash").empty().text("Email has been sent. Please check inbox !");
}
});
});
</script>
Server
app.post('/email', function(req, res) {
var toSend = req.files;//no files, this is empty
sendEmail(req.body, toSend);//email is sent successfully
res.send('text to send back to client');
});
req.files is empty. If I make a post request inside of an html form the file and email is sent correctly, but once I make the form submission as a ajax request or express call, the file is not sent. Any help would be appreciated.