1
votes

I have the following request and I would like to write a post request in nodejs:

POST /rest-api/hashDb/createAndUpload HTTP/1.1

Host: 192.168.101.54

Connection: keep-alive

Content-Length: 428

Origin: https://192.168.101.54

User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36

Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryQGLkZW0bVDsvWPEY

Accept: /

Referer: https://192.168.101.54/ufed/index.html

Accept-Encoding: gzip, deflate, br

Accept-Language: en-US,en;q=0.9,es;q=0.8,he;q=0.7

Cookie: JSESSIONID=s3a5sjc6wp1y1k9hv5advlf3a

This is the code I wrote but it does not work (the file does not get uploaded):

var FormData = require('form-data');
var fs = require('fs');
var request = require("request")
// var XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest;

let filePath = "C:\\Temp\\directory.txt" 
let myFile = fs.readFileSync(filePath,'utf8');
var formData = new FormData();
formData.append("myFile", myFile, "directory.txt");
var bounding = {"id":null,"type":"HashDbDto","name":"jorge1","fileType":"TXT","version":"1.2","redaction":false,"categories":[],"format":"MD5"};
formData.append("myFile", JSON.stringify(bounding));

request({
    headers: {'content-type': 'multipart/form-data; boundary=----WebKitFormBoundaryeiNygPyQcm8jomRB'},
    url: "https://192.168.101.54/rest-api/hashDb/createAndUpload",
    method: "POST",
    form: formData
});

What is your solution?

1
If you are looking for a solution to upload file using an ajax request and nodejs as backend, you can take help from this link : github.com/arjun-707/login-logout-jwt-nodejs . See the section 'profile pic upload'Arjun Singh

1 Answers

0
votes

Use formData key instead of form key

request({
   headers: {'content-type': 'multipart/form-data; boundary=----WebKitFormBoundaryeiNygPyQcm8jomRB'},
   url: "https://192.168.101.54/rest-api/hashDb/createAndUpload",
   method: "POST",
   form: formData
})

See https://www.npmjs.com/package/request . For multipart/form-data we use the form-data library by @felixge. For the most cases, you can pass your upload form data via the formData option.