Katie
Katie

Reputation: 48218

How to access variable from Ajax FormData.append?

I am sending an uploaded file from my HTML form to my server and am trying to add a custom attribute to FormData(), but it's not showing up on my server side.

I add my custom attribute by doing var formData = new FormData();, then appending by doing formData.append("airlinename",airline_name);, but once I get the data on the Server side, I look in the req object and can't find airlinename. How do I access my custom attribute?

I am able to access the file just fine, but I can't find how to access the custom attribute I appended to formData.

HTML Form

<form role="form">
    <input type="text"  id="load_db_name" name="load_db_name">
    <input type="file"  id="load_db_dir" name="load_db_dir">
</form>
<button id="load_generateDiagram" onClick="loadPastDiagram();" type="button">Load</button>

Client JS

function loadPastDiagram()
{   
    var db_dir = document.getElementById('load_db_dir').files[0] || null;
    var _files = [db_dir];
    var airline_name = document.getElementById('load_db_name').value.trim();
    loadDiagram(airline_name,_files);
}

function loadDiagram(airline_name, files)
{
    var formData = new FormData();
        for (var f in files) {
            formData.append("files", files[f]);
        }
        formData.append("airlinename",airline_name); //<--- can't find this on the server side
        $.ajax({
            url: '/loadDiagram', 
            type: 'POST',
            success: function(res) {
                console.log("Success");
            },
            error: function(err) {
                console.log("Error ",err);
            },
            data: formData,

            //Options to tell jQuery not to process data or worry about content-type.
            cache: false,
            contentType: false,
            processData: false
        });
}

Server JS

app.post('/loadDiagram', function(req,res){
    console.log("[FILES]" + JSON.stringify(req.airlinename));
    console.log("[FILES]" + JSON.stringify(req.files.airlinename));
    console.log("[FILES]" + JSON.stringify(req.files.files));
});

Output

[DEV]  [FILES]undefined
[DEV]  [FILES]undefined
[DEV]  [FILES]{
    "fieldName": "files",
    "originalFilename": "Tool_fresshhh.tar.gz",
    "path": "../Output-Files/2833-fwh0ql.tf9od2t9.gz",
    "headers": {
        "content-disposition": "form-data; name=\"files\"; filename=\"Tool_fresshhh.tar.gz\"",
        "content-type": "application/x-gzip"
    },
    "ws": {
        "_writableState": {
            "objectMode": false,
            "highWaterMark": 16384,
            "needDrain": true,
            "ending": true,
            "ended": true,
            "finished": true,
            "decodeStrings": true,
            "defaultEncoding": "utf8",
            "length": 0,
            "writing": false,
            "corked": 0,
            "sync": false,
            "bufferProcessing": false,
            "writecb": null,
            "writelen": 0,
            "bufferedRequest": null,
            "lastBufferedRequest": null,
            "pendingcb": 0,
            "prefinished": true,
            "errorEmitted": false,
            "bufferedRequestCount": 0,
            "corkedRequestsFree": {
                "next": {
                    "next": null,
                    "entry": null
                },
                "entry": null
            }
        },
        "writable": false,
        "domain": null,
        "_events": {
            "error": [null],
            "close": [null]
        },
        "_eventsCount": 2,
        "path": "../Output-Files/2833-fwh0ql.tf9od2t9.gz",
        "fd": null,
        "flags": "w",
        "mode": 438,
        "autoClose": true,
        "bytesWritten": 449781,
        "closed": true
    },
    "size": 449781,
    "name": "Tool_fresshhh.tar.gz",
    "type": "application/x-gzip"
}

Versions

Upvotes: 0

Views: 393

Answers (1)

Louys Patrice Bessette
Louys Patrice Bessette

Reputation: 33933

I know this is "uncool"...

But I saw this question as it was posted, more than 1 hour ago, and saw (quite fast!!) the solution posted as a comment. I waited on him or her to post it, so I could learn something.

But since Jaromanda X was actually last seen 5 minutes ago without posting the answer...

I guess he or she is not really interested about rep. points!
So just to mark this question as answered... ;)

Server JS

app.post('/loadDiagram', function(req,res){
    console.log("[FILES]" + JSON.stringify(req.body.airlinename));    // <-- 
    console.log("[FILES]" + JSON.stringify(req.files.files));
});

«First one to post it, gets it! »

Upvotes: 1

Related Questions