I did the following request with JS and it worked. Now trying to adapt in for react and getting an empty object being posted. Below just bits of code, but basically I am generating pdf and aiming to send it to backend:
const doc = new jsPDF();
const blob = doc.output('blob');
const email = formData.emailRequired;
const formDataToSend = new FormData();
formDataToSend.append('email', email);
formDataToSend.append('file', blob);
console.log(formDataToSend)
fetch('http://localhost:8080/api/contract',
{
method: 'POST',
data: formDataToSend,
processData: false,
contentType: false,
});
Unfortunatelly on submit I get FormData {} - so it's an empty object. Why?
FormData is not an empty object, it is displayed like this in the console.
If you want to display all entries, then use this approach
console.log([...formDataToSend.entries()])
Related question How to inspect FormData?
Related
I am in a Node.JS application. (Node version 14 if that matters)
Also I am using node-fetch (v2) to send my request.
I am trying to send a Send Fax Request to Documo. The documentation can be found here: https://docs.documo.com/#da8dc725-8327-470c-83e4-34b40205cfa2.
As part of the request I want to send a pdf file that I have stored in S3. I have the following code to accomplish that:
const s3Object = await s3Client.send(
new GetObjectCommand({
Bucket: bucket,
Key: key,
})
const formData = new FormData();
formData.append("faxNumber", faxNumber);
formData.append("coverPage", "true");
formData.append("recipientName", recipientName);
formData.append("senderName", senderName);
formData.append("subject", subject);
formData.append("notes", note);
formData.append("webhookId", webhookId);
formData.append("attachments", s3Object.Body);
// ERROR: File extension 'pdf%22&x-id=getobject' is not allowed. Allowed formats: doc,docx,fodt,gif,htm,html,jpeg,jpg,odp,ods,odt,pdf,png,ppt,pptx,rtf,tif,tiff,txt,xls,xlsx,csv
const response = await fetch(`${BASE_DOCUMO_URL}/v1/faxes`, {
method: "POST",
headers: {
Authorization: DEMO_API_KEY,
ContentType: "multipart/form-data",
},
body: formData,
});
I am getting the following error from Documo:
"File extension 'pdf%22&x-id=getobject' is not allowed. Allowed formats: doc,docx,fodt,gif,htm,html,jpeg,jpg,odp,ods,odt,pdf,png,ppt,pptx,rtf,tif,tiff,txt,xls,xlsx,csv"
From what I understand it looks like the GetObjectCommand from S3 is appending an x-id in the file stream which the Documo client is not happy with. Ideally I don't want to recreate this file in memory and I just want to take the result from S3 to send through my POST request. (Although I could be convinced to just do that if there is no better option or I don't need to worry about holding files in memory).
What are my options. I've tried playing around with ResponseContentDisposition in GetObjectCommand to no avail
I have a Node.js (16.13.1) REST API using Express and one of my endpoints receives one or more uploaded files. The client (web app) uses FormData into which the files are appended. Once they're submitted to my API, the code there uses multer to grab the files from the request object.
Now I'm having trouble trying to send those same files to another API. multer attaches the files to req.files and each file object in that array has several properties one of which is buffer. I tried using the stream package's Duplex object to convert this buffer to a stream so that I could append the file to another FormData object, but when the server the second API is running on receives the request, I get an error from the web server saying that "a potentially dangerous request.form value was detected from the client.".
Any suggestions?
I am working on a nest project I was also facing this issue did some research and found that we need to create a Readable from the Buffer of that file and it's working for me.
// Controller
#UseInterceptors(FileInterceptor('file'))
async uploadFile(#UploadedFile() file: Express.Multer.File) {
return this.apiservice.upload(file);
}
// Service
uploadFile(file: Express.Multer.File) {
const readstream = Readable.from(file.buffer)
console.log(readstream)
const form = new FormData();
form.append('file', file, { filename: extra.filename });
const url = `api_endpoint`;
const config: AxiosRequestConfig = {
headers: {
'Content-Type': 'multipart/form-data'
},
};
return axios.post(url, form, config);
}
We have a problem with the fleet.ls.hereapi.com when uploading a new layer for geofencing.
const myId = 'MYLAYER'; // just a id to check
zip.file('data.wkt', `NAME\tWKT\n${myId}\t${wkt}`);
const content = await zip.generateAsync({ type: 'nodebuffer' });
const formData = new FormData();
formData.append('zipfile', content);
await axios.post(config.HERE_MAPS_UPLOAD_ENDPOINT, formData, {
headers: {
'content-type': 'multipart/form-data',
},
params: {
apiKey: config.HERE_MAPS_REST_API_KEY,
layer_id: myId,
},
});
We get a bad request without a message and do not know what the problem is. The same implementation works in the Frontend (with 'blob' as zip type). Is there a parameter to get a better error message from the api?
We got the instructions how to implement it from this tutorial: https://www.youtube.com/watch?v=Ayw9GcS1V-8 and as I mentioned it works fine in the frontend. Also it works if I write a file in node and upload it via curl. Thank you for any help in advance!
Edit: I'm getting the following issue from the API: 'Multipart should contain exactly one part but contains 0'
I fixed it!
The problem was that the api needed a filename for the form data. This filename can be provided as third parameter as described here.
So I basically changed formData.append('zipfile', content); to formData.append('zipfile', content, zipfile.zip); and it worked.
Hope this will help somebody in the future!
I use HttpClient in Angular to send formdata to Nodejs.
resetPasswordRequest(email){
this.httpOptions={
headers: new HttpHeaders({
'Content-Type':'application/x-www-form-urlencoded'
})
}
const formData = new FormData();
formData.append('email',email);
return this.http.post("http://localhost:3001/forgotPassword",formData,this.httpOptions);
}
Later in NodeJS,I have app.use(bodyParser.urlencoded({extended:true}).
I am able to get req.body but in a different format as below:
{ '-----------------------------24875245787704\r\nContent-Disposition: form-data; name':
'"email"\r\n\r\abcd#gmail.com\r\n-----------------------------24875245787704--\r\n' }
I am not sure what has been missed. Could you please clarify and help get value of email? I get req.body.email as undefined.
From MDN FormData:
It uses the same format a form would use if the encoding type were set to "multipart/form-data"
which explains why you're getting data in that format.
You could use angular's HttpParams instead:
const formData = new HttpParams();
formData.set('email', email)
return this.http.post("http://localhost:3001/forgotPassword", formData.toString(), this.httpOptions);
toString gives you urlencoded format. From docs:
Serialize the body to an encoded string, where key-value pairs (separated by =) are separated by &s
you need to parse formData in nodejs. see this question or find similar. also are you sure you need to use formData? you can just send object in body
How can I upload a file from my angular controller. I am doing something like, On ng-click I am calling upload_file() function which is declared inside my controller. And I want to use something like this
$http.post("url", data).success().error();
url is of node upload service. It's working fine when I use like . But without using action there, I want to upload it from my function.
But I am not getting how to attach the file selected to the data here. I want to send some data along with file. Can I upload it in the way I am trying? please help me...
You can use angular-file-upload library:
Basically you need to $http.post like this:
$http({
method: 'POST',
url: config.url,
headers: { 'Content-Type': false },
transformRequest: function (data) {
var formData = new FormData();
formData.append('file', myFile);
for (key in myData) {
formData.append(key, myData[key]);
}
return formData;
}
}).success().error().progress()
The library supports IE with flash polyfill which normally doesn't support FormData so you cannot get the file object from the <input file...>.