javascript - how to upload and post file to node express server -
i have traditional html email form sending post request file user can upload. want able flash success message once email sent, , in order need either use ajax or make post request using express - , not rely on traditional html form submission.
how send file (not filepath string) server? i'm assigning input element id , and grabbing value. grabs string of file path file, , not send 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, empty sendemail(req.body, tosend);//email sent res.send('text send client'); });
req.files empty. if make post request inside of html form file , email sent correctly, once make form submission ajax request or express call, file not sent. appreciated.
file uploading express 4.0: req.files undefined
the body-parser module handles json , urlencoded form submissions, not multipart (which case if you're uploading files).
for multipart, you'd need use connect-busboy or multer or connect-multiparty (multiparty/formidable used in express bodyparser middleware). fwiw, i'm working on higher level layer on top of busboy called reformed. comes express middleware , can used separately.
edit:
it looks you're not sending file $.post()
. can use formdata
object lets compile set of key/value pairs (including file input) send ajax. transmitted data in same format form’s submit method use send data if form’s encoding type set multipart/form-data. https://developer.mozilla.org/en-us/docs/web/api/formdata/using_formdata_objects
Comments
Post a Comment