简体   繁体   中英

how to upload and post file to node express server

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.

File uploading with Express 4.0: req.files undefined

The body-parser module only handles JSON and urlencoded form submissions, not multipart (which would be the case if you're uploading files).

For multipart, you'd need to use something like connect-busboy or multer or connect-multiparty (multiparty/formidable is what was originally used in the express bodyParser middleware). Also FWIW, I'm working on an even higher level layer on top of busboy called reformed. It comes with an Express middleware and can also be used separately.

Edit:

It looks like you're not sending the file with the $.post() . You can use the FormData object which lets you compile a set of key/value pairs (including File input) to send with ajax. The transmitted data is in the same format that the form's submit method would use to send the data if the form's encoding type were set to multipart/form-data. https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM