简体   繁体   中英

dropzone nodejs file upload

I'm tyring to use DropZone to upload a file to my nodejs server. However, I can't figure out how to get a file handle when the post hits my nodejs server. Here's how I instantiate the DropZone in my html:

<form action="/file-upload" class="dropzone" id="logoDropZone">
  <input type="hidden" name="userName" value="user"/>
</form>

Then, in my nodejs server I have the following code:

app.post('/file-upload', function (request, response) {
    console.log("Route: '/file-upload' ");
    console.log("File upload request from user: " + request.body.userName);
    // Get a file handle, read the file and then write it out to the file system.

    ...  

  });

I can see that this code is getting executed. I'm also able to access values in input fields (see the hidden input) via the request object. But, how do I access the file itself so that I can write it to the server filesystem?

I found the answer to this question. The following code uploads the file to the server:

app.post('/file-upload', function (request, response) {

  fs.readFile(request.files.file.path, function(err, data) {

    var newPath = __dirname + "/public/img/xspectra/customlogo.png";
    fs.writeFile(newPath, data, function (err) {
      console.log("Finished writing file..." + err);
      response.redirect("back");
    });

  });

});

So that others don't get stuck on this same issue, I'll explain what I was NOT doing correctly:

1) Though the form element has no "name" attribute, files can be accessed in the node request object via the name, "file". This can be seen in the above code as:

request.files.file.path

Where: 'file' is the "name" of the form.

2) This code was found at the following site (to give credit and to provide constructive criticism below): http://howtonode.org/af136c8ce966618cc0857dbc5e5da01e9d4d87d5/really-simple-file-uploads

Though I definitely appreciate the owner creating the documentation, it could use some improvements in order to reduce confusion. Mainly, the documentation needs to be updated to explicitly explain point number '1)' above.

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