Search code examples
jquerynode.jsmime-typescontent-typefs

fs.writeFile is not returning pdf file as it's content is


I'm getting some file from some link(basically anchor href) using ajax then I'm sending the content to node server as follows:

<a class="myTag" href="/getFiledata?uid=7674&&pass=75876789">Download</a>

.

jQuery.get(jQuery("a.myTag").attr("href"), function(data, status){
            console.log("typeof data: ",typeof data);
            jQuery.ajax({
                url : 'https://7c099919.ngrok.io/fildta?fileTyp=naukriDta',
                type : 'POST',
                contentType: 'application/json',
                dataType: 'json',
                data : JSON.stringify({bdy:data}),
                arrayKey:'',
                processData: false,  // tell jQuery not to process the data
                success : function(data) {
                    console.log(data);
                }
            });
            console.log("Data: ",data );
        }); 

I'm listning and writing data on server as follows:

function(req, res, next){
                var fd=path.join(__dirname,"../upld/tmp.pdf");
                console.log("req body:  ",JSON.stringify(req.body));
                fs.writeFile(fd, req.body.bdy, function(err) {
                    if (err){
                        console.log(fd,"\n\n\n\n\n Can not write to above file:\n\n",err);
                    }else {
                        console.log(fd,' is Done');
                    }
                });
                console.log("req query:  ",req.query);
                res.send({"msg":"File is uploaded"});
            }

but when I do read created pdf file using any reader it shows blank but when I read its content using notepad++ the content is same as It was on client.

the content of file is as follows:

Data: %PDF-1.5
%����
24 0 obj
<<
/Linearized 1
/L 121184
/H [ 1971 370 ]
/O 26
/E 98912
/N 4
/T 120577
>>
endobj

xref
24 70
0000000017 00000 n
0000001869 00000 n
0000002341 00000 n
0000002744 00000 n
0000002924 00000 n
0000003187 00000 n
0000003532 00000 n
0000003720 00000 n
0000003999 00000 n
0000008165 00000 n
0000008222 00000 n
0000008397 00000 n
0000008655 00000 n
0000008884 00000 n
0000009034 00000 n
0000009064 00000 n
0000009246 00000 n
0000009328 00000 n
0000009601 00000 n
0000018049 00000 n
0000018198 00000 n
0000018570 00000 n
0000018753 00000 n
0000019026 00000 n
0000025387 00000 n
0000025414 00000 n
0000025569 00000 n
0000025599 00000 n
0000025786 00000 n
0000026064 00000 n
0000036489 00000 n
0000036867 00000 n
0000037320 00000 n
0000037509 00000 n
0000037787 00000 n
0000045277 00000 n
0000045492 00000 n
0000045642 00000 n
0000045672 00000 n
0000045854 00000 n
0000046128 00000 n
0000061832 00000 n
0000062215 00000 n
0000062645 00000 n
0000062828 00000 n
0000063102 00000 n
0000069388 00000 n
0000069443 00000 n
0000069592 00000 n
0000069622 00000 n
0000069803 00000 n
0000070073 00000 n
0000073366 00000 n
0000073411 00000 n
0000073718 00000 n
0000073873 00000 n
0000073903 00000 n
0000074090 00000 n
0000074369 00000 n
0000083843 00000 n
0000084123 00000 n
0000084551 00000 n
0000084699 00000 n
0000084729 00000 n
0000084909 00000 n
0000085193 00000 n
0000093386 00000 n
0000093570 00000 n
0000093941 00000 n
0000001971 00000 n
trailer
<<
/Size 94
/Prev 120566
/Info 23 0 R
/Root 25 0 R
/ID [<4e891be7c450bedc9528eba318fe1823><4e891be7c450bedc9528eba318fe1823>]
>>
startxref
0
%%EOF

25 0 obj
<<
/Type /Catalog
/Pages 22 0 R
/Lang (en-IN)
/MarkInfo << /Marked true >>
>>
endobj
93 0 obj
<<
/S 188
/Filter /FlateDecode
/Length 280
>>
stream
x�c```b``������*� Ȁ

I'm naive in MIME-TYPE and file content concept. I think somewhere I'm missing to set certain data(MIME-TYPE,content-type etc) before writing the file.

Basically My aim is to redirect the file got from anchor to my node server.


Solution

  • As @Tomalak suggested to use xhr2. I just added responseType/dataType to blob/binary depending upon javascript/jQuery it worked.

    the client code is as follows: - First method:

    var xhr = new XMLHttpRequest();
       xhr.open('GET', jQuery("a.myTag").attr("href"), true);
       xhr.responseType = 'blob';
    
       xhr.onload = function(e) {
           if (this.status == 200) {
               // get binary data as a response
               var blob = this.response;
               var base64data;
               var reader = new window.FileReader();
               reader.readAsDataURL(blob);
               reader.onloadend = function() {
                   base64data = reader.result;
                   var myDta={bdy:base64data};
                   console.log("myDta",myDta);
                   jQuery.ajax({
                       url : 'https://7c099919.ngrok.io/fildta?fileTyp=naukriDta',
                       type : 'POST',
                       data : myDta,
                       success : function(data) {
                           console.log(data);
                       }
                   });
               };
           }
       };
    
       xhr.send();
    

    Second method

    $.ajax({
      url: jQuery("a.myTag").attr("href"),
      type: "GET",
      dataType: "binary",
      processData: false,
      success: function(result){
          // same stuffs with binary data as above
      }
    });
    

    The server code is as follows:

    function(req, res, next){
                    var fd=path.join(__dirname,"../upld/tmp.pdf");
                    console.log("req body:  ",JSON.stringify(req.body));
                    var base64Data = req.body.bdy.replace(/^data:application\/pdf;base64,/, "");
                    console.log("base64Data  ",base64Data);
                    fs.writeFile(fd, base64Data,'base64', function(err) {
                        if (err){
                            console.log(fd,"\n\n\n\n\n Can not write to above file:\n\n",err);
                        }else {
                            console.log(fd,' is Done');
                        }
                    });
                    console.log("req query:  ",req.query);
                    res.send({"msg":"File is uploaded"});
                }
    

    Wohoo.. It worked :)

    Strictly speaking XHR2 isn't HTML5. However, it's part of the incremental improvements browser vendors are making to the core platform.