Kong / unirest-nodejs

Unirest in Node.js: Simplified, lightweight HTTP client library.
http://unirest.io/nodejs
MIT License
953 stars 167 forks source link

Problem sending files via HTTP request for TestRail. #141

Open fabio-morais-Exaud opened 1 year ago

fabio-morais-Exaud commented 1 year ago

Hello.

I'm working on automating e2e test results to Testrail and I'm currently having problems sending files as attachments.

Testrail API allows to send files via a multi-part/form-data, but I having trouble writing the request.

Here is the code:

 /**
   * Post request to upload a file using multipart/form-data
   * See https://www.npmjs.com/package/unirest#request-form-methods
   * See https://support.gurock.com/hc/en-us/articles/7077196481428-Attachments#addattachmenttorun
   * @param api - command to pass in the HTTP request
   * @param attachment - the attachment Interface that contains info of the screenshot
   * @param callback - function that executes after getting the result from the HTTPS request.
   * @param error - function to execute after error occours
  */
  private _sendFile(api: String, attachment: TestRailAttachment,  callback: Function, error?: Function) {
    console.log(attachment);
    //let form = new FormData();
    //form.append('attachment', fs.createReadStream(attachment.path));
    //console.log(form);
    request("POST", `${this.base}/api/v2/${api}`)
    .headers({
      'content-type': 'multipart/form-data'
    })
    .field({'parameter' : 'value'})
    .attach({
      'attachment': fs.createReadStream(attachment.path) 
    })
    .auth( this.options.username, this.options.password)
    .then((res) => {
      console.log(res.body)
      callback(res.body);
    });
  }