Wednesday, 7 June 2017

NodeJS File From Form

I'm having some trouble trying to handle a file upload input with NodeJS in a form I'm trying to write. The HTML for the form is generated automatically and the tags for the input are set correctly:

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

The form data is parsed and submitted to the Node server through the following code:

$('form').submit((e) => {
  e.preventDefault();

  const formData = new FormData(this);

  $.ajax({
    type: 'POST',
    url: '/tickets',
    cache: false,
    contentType: false,
    processData: false,
    data: formData,
    success: null,
    error: null
  })

The form data is an object that is sent to the server, with all the other fields being strings that are easy to parse. However, this is where I run into issues, as the file attachments field returns a Buffer object as such:

<Buffer 89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00 00 02 3f 00 00 01 ea 08 06 00 00 00 eb b7 2f 36 00 00 00 01 73 52 47 42 00 ae ce 1c e9 00 00 00 04 ... >

As my end goal here is to upload these attached files to Zendesk and Jira, both of those APIs require either the path to the file or a fs.readStream object, which I can't seem to get from the Buffer. How do I go about passing the uploaded file to the server in the proper way? I'm almost positive that there is a better way to go about this, any help would be appreciated.



via AJwr

No comments:

Post a Comment