Search code examples
javascriptmultipartform-dataform-data

parsing a formdata object with javascript


My company uses a propitiatory application server in which the server side programs are written in javascript (not node.js) . This is a very initial thing and support isn't that good

Now here is my problem :

I am having to process an uploaded csv on the server side .. I am using the super answer at How can I upload files asynchronously? (passing the formdata object with jquery) and i am able to access the sent file on the server side . But how do i parse it out ?

It looks like this

------WebKitFormBoundaryU5rJUDxGnj15hIGW
Content-Disposition: form-data; name="fileToUpload"; filename="test.csv"
Content-Type: application/vnd.ms-excel

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

------WebKitFormBoundaryU5rJUDxGnj15hIGW--

I'm really confused how to handle this file with plain javascript on the server side.

Please help.


Solution

  • Ok so , i managed to do this myself. I tested it out of a couple of browsers and noticed that the header was 3 lines and the footer was 1 line.

    I just wrote one simple parser that splits the file by the newline character and put its into an array line by line.

    This helps me in processing till now .

    function doProcess()
    {
    
    var i=0;
    var str = '';
    var arrayList = [];
    
    for (i=0;i<fileContent.length;i++)
    {
        if (fileContent[i] !== '\n')
        {
            str += fileContent[i];
        }
        else
        {
            str = str.replace("\r","");
            if (trim(str) !== "")
            {
                arrayList.push(str);
            }
            str = '';
        }
    }
    
        // Remove header
        arrayList.splice(0,3);
    
        // Remove footer
        arrayList.splice(arrayList.length-1,1);
    
        // arrayList is an array of all the lines in the file
        console.log(arrayList); 
    }