0

I am using nodeJS and I would like to upload a file to the server. I have pug page where the user fill all the information and choose a file with filechooser. Then I want to send all the information on the page to the server. Therefore, I am using ajax to send a json object and given that file object can not be send through a json object I convert the File object to a json object like this:

function uploadGenome() {
    var file = $(':file')[0].files[0];
    var fileObject = {
        'lastMod': file.lastModified,
        'lastModDate': file.lastModifiedDate,
        'name': file.name,
        'size': file.size,
        'type': file.type
    };
    return fileObject;
}

Then I add everything in a Json object:

    var data = {};
    data.file = uploadGenome();
    data.name = inputs[0].value;
    data.description = inputs[1].value;
    data.start = inputs[3].value;
    data.end = inputs[4].value;

And finally, I send everything with ajax:

 $.ajax({
        type: 'POST',
        data: JSON.stringify(data),
        contentType: 'application/json',
        url: url,
        success: function (data) {
            console.log('success');
            console.log(JSON.stringify(data));
            if (data === 'done')
            {
                window.location.href = "/";
            } else {
                alert('Error Creating the Instance');
            }
        },
        error: function () {
            console.log('process error');
        }
    });

On the server side with NodeJS I get everything, but now how could I copy the file that I get in data.file on the server ? I mean create a copy on the project folder which is on a server.

PierBJX
  • 35
  • 2
  • 9
  • What are you asking? You're saying you're getting the information on the server. Just create a new file with the contents of the received information. https://nodejs.org/api/fs.html – Simon Hyll Apr 07 '18 at 15:44
  • No, in fact, I save the information data.name, data.description, data.start and data.end in a database. And I would like at the same time to copy the file @SimonHyll – PierBJX Apr 07 '18 at 15:49
  • It looks like you never transfer the file itself as your payload just contains file metadata. – lukas293 Apr 07 '18 at 15:59
  • I have seen that I could use formData but it means that I will have to send two ajax one for the file and one for the information (description, start, end, name) that I want to save to the database @lukas293 – PierBJX Apr 07 '18 at 16:02
  • https://stackoverflow.com/questions/4006520/using-html5-file-uploads-with-ajax-and-jquery – lukas293 Apr 07 '18 at 16:07
  • Alright, basically he is reading the content of the file and then sending it. Thanks – PierBJX Apr 07 '18 at 16:15
  • Add `file: 'contents as string'` to the json object that you're sending, you don't need any special magic to send a file. – Simon Hyll Apr 07 '18 at 19:44

0 Answers0