D
D
Danil2015-01-27 17:34:55
JavaScript
Danil, 2015-01-27 17:34:55

How to upload a file in nodejs?

There is a form:

<form id="photo-form" name="upload" enctype="multipart/form-data" method="post" action="/upload">
        Виберіть зображення, які бажаете загрузити.
      <input id="files-field" type="file" multiple="multiple" />
      <input type="submit">
      <a class="send-files button tiny small-4">Загрузити</a>
  </form>

Js submit processing:
(function(){
  $('body').on('click', '.send-files', function() {

    var formData = new FormData(),
      items = $('#files-field')[0].files
      formData.append('file', items);

    $.ajax({
      type: "POST",
      url: '/upload',
      data: formData,
      processData: false,
      success: function(){
        //window.location.href = '/';
      }
    });
  })
}());

NodeJs:
upload.post('/', function(req, res) {

  var form = new formidable.IncomingForm();
    form.uploadDir ='..//public/images';
    form.keepExtensions = false;
    form.type = 'multipart/form-data';
    form.multiples = true;

    form.on('error', function(err) {
          console.log(err);
      });

    console.log(form);

    form.on('end', function(fields, files) {
      console.log('end')
    });

      form.parse(req, function(err, fields, files) {
        console.log(err, fields, files)
      });

   		res.end();
  
});

Console output:
{ domain: null,
  _events: { error: [Function] },
  _maxListeners: 10,
  error: null,
  ended: false,
  maxFields: 1000,
  maxFieldsSize: 2097152,
  keepExtensions: false,
  uploadDir: '..//public/images',
  encoding: 'utf-8',
  headers: null,
  type: 'multipart/form-data',
  hash: false,
  multiples: true,
  bytesReceived: null,
  bytesExpected: null,
  _parser: null,
  _flushing: 0,
  _fieldsSize: 0,
  openedFiles: [] }
end
null {} {}

Approximately the same situation with other middleware for downloading files - an empty request comes.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Denis Bogdanov, 2015-01-27
@den-bogdanov

Perhaps, although not sure, you need to replace the string in the argument of the post method
upload.post ('/upload' , function(req, res) {

T
Test Test, 2015-01-27
@cubooks

Good evening! I think that the problem is that the back-end does not receive the correct data from the form.
That is, either AJAX is sent incorrectly, or the form is set incorrectly. Try to set the form with a file with id name, not id.

<input type="file" name="upload" multiple="multiple">

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question