Intro:
As of Feb 11th 2020,
request
is fully deprecated. No new changes are expected to land. In fact, none have landed for some time. This package is also deprecated because it depends on request. - https://github.com/request/request-promise
I have been using npm request-promise
for sending files from node backend to restify
endpoints. Unfortunately request-promise
is being deprecated so I am switching to node-fetch
instead.
with request-promise I was able to construct a request something like this:
const formData = {
file: {
value: file,
options: {
filename: 'someFileName.xlsx',
contentType: 'image/jpg'
}
}
}
const requestOptions = { ...., formData };
return requestPromiseFetch(url, requestOptions).then(response => { ....});
And get the file from the request under "files" req.files.file.path
This also works when getting files from browser fetch, which in chrome network request looks like this:
"postData": {
"mimeType": "multipart/form-data; boundary=----WebKitFormBoundaryE6T9nfRvBAScnlki",
"text": "------WebKitFormBoundaryE6T9nfRvBAScnlki\r\nContent-Disposition: form-data; name=\"file\"; filename=\"importTest.xlsx\"\r\nContent-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\r\n\r\n\r\n------WebKitFormBoundaryE6T9nfRvBAScnlki--\r\n",
"params": [
{
"name": "file",
"value": "(binary)"
}
]
}
On the backend I nicely receive the file from the browser request like this:
async function receivingFile (req) {
console.log(req.files);
const result = await schema.importer.importingFile({ fullPath: req.files.file.path });
return { result };
}
console.log prints:
{
file: File {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
size: 4803,
path: '/var/folders/jv/py0twd4d2dgfslwry_ch8_tm0000gp/T/upload_3ba513d3d1ee5912c1d20067c3775c47.xlsx',
name: 'importTest.xlsx',
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
hash: null,
lastModifiedDate: 2020-05-05T11:18:24.421Z,
_writeStream: WriteStream {
_writableState: [WritableState],
writable: false,
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
path: '/var/folders/jv/py0twd4d2dgfslwry_ch8_tm0000gp/T/upload_3ba513d3d1ee5912c1d20067c3775c47.xlsx',
fd: null,
flags: 'w',
mode: 438,
start: undefined,
autoClose: true,
pos: undefined,
bytesWritten: 4803,
closed: true
}
}
}
I wan't the received request made by node-fetch
to look the same, so that I can get the file just like I get it when it is sent by the browser fetch, and as used to be when sent by request-promise
I have been reading through this question: How to send a file in request node-fetch or Node?
But none of the answers helped me produce the same result as I was able to when using request-promise
to construct the http request.