I am sending a formdata to an endpoint that requires the following data:
token_key,
customer_id,
folder_id,
document_id,
file
but I get an error when sending it, the steps I do are the following:
html file
submitBtn.addEventListener("click", function (e) {
if (is_signed) {
var dataUrl = canvas.toDataURL();
var image = dataURItoBlob(dataUrl);
var file = new File([image], 'firma.png', {
type: 'image/png'
});
var folder_id = location.search.slice(1).split("&")[0].split("=")[1]
var document_id = location.search.slice(1).split("&")[1].split("=")[1]
const formdata = new FormData();
formdata.append('document_id', parseInt(document_id));
formdata.append('folder_id', parseInt(folder_id));
formdata.append('file', file)
axios.post('/send-signature', formdata, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}, false)
Js file
router.post("/send-signature", (req, res) => {
const url_expa_signature = `${process.env.BASE_URL_EXPA}/upload-documents`
const document_id = req.body.document_id
const folder_id = req.body.folder_id
const file = req.files.file
const token_key = process.env.TOKEN_KEY
const customer_id = process.env.CUSTOMER_ID
const formdata = new FormData();
formdata.append('token_key', token_key);
formdata.append('customer_id', customer_id);
formdata.append('folder_id', folder_id);
formdata.append('document_id', document_id);
formdata.append('file', file);
axios({
method: 'post',
url: url_expa_signature,
data: formdata,
})
})
and the following error is
TypeError: source.on is not a function
any suggestion?
It was a problem with the endpoint that i consume, i solve it calling to suport and they fix the bug.
Related
I am attempting to use a form in Remix to add a file and then upload that file to WhatsApp using their Cloud API Media Upload endpoint. Below is my initial code within the action. The current error I am receiving is message: '(#100) The parameter messaging_product is required.. I feel like this error may be misleading based off the form data I have appended with the "messaging_product".
export async function action({ request, params }: ActionArgs) {
const uploadHandler = unstable_composeUploadHandlers(
async ({ name, contentType, data, filename }) => {
const whatsAppPhoneId = process.env.WHATSAPP_PHONE_ID;
const whatsAppToken = process.env.WHATSAPP_ACCESS_TOKEN;
const dataArray1 = [];
for await (const x of data) {
dataArray1.push(x);
}
const file1 = new File(dataArray1, filename, { type: contentType });
const graphApiUrl = `https://graph.facebook.com/v15.0/${whatsAppPhoneId}/media`;
const formData = new FormData();
formData.append("file", file1);
formData.append("messaging_product", "whatsapp");
formData.append("type", contentType);
try {
const imageMediaResponse = await fetch(graphApiUrl, {
method: "POST",
headers: {
Authorization: `Bearer ${whatsAppToken}`,
"Content-Type": "multipart/form-data",
},
body: formData,
});
const imageMedia = await imageMediaResponse.json();
return imageMedia?.id;
} catch (error) {
console.error(error);
}
const whatsAppMediaId = await uploadWhatsAppImageMedia(
whatsAppPhoneId,
whatsAppToken,
data,
filename,
contentType
);
}
);
const formData = await unstable_parseMultipartFormData(
request,
uploadHandler
);
}
This is my code:
async function uploadDocForPlagScan(params) {
try {
console.log(params);
const token = await getTokenForDocumentUpload();
const { data: arr } = await axios.get(
"https://kmsmediasvcstorage.blob.core.windows.net/knowledgesfqueryuat/6-P.pdf",
{ responseType: "arraybuffer" }
);
const apiKey = "idF******************";
const fileName = "WHNTMB.pdf";
const filePath = path.join(__dirname, "WHNTMB.pdf");
const fileContent = await fs.readFileSync(filePath);
const formData = new FormData();
formData.append("fileUpload", fileContent, fileName);
formData.append("language", "en");
const headers = {
"Content-Type": "multipart/form-data",
Authorization: `Bearer ${apiKey}`,
};
const response = await axios.post(
`https://api.plagscan.com/v3/documents?access_token=${token.data}`,
{ fileUpload: formData },
{ headers }
);
console.log(response.data);
} catch (error) {
p = error;
}
}
I tried to upload file in node js by making post call in https://api.plagscan.com/v3/documents?access_token=amdsfa
In my node application, I want to get a file from one server, and then upload it into another server. I have the following code:
const axios = require("axios");
const FormData = require("form-data");
const { createWriteStream, createReadStream } = require("fs");
const response = await axios({
url: "https://first-server/image.png",
method: "GET",
responseType: "stream",
});
await new Promise((res) => {
response.data.pipe(
createWriteStream("someFile.png").on("finish", () => {
res();
})
);
});
const form = new FormData();
form.append("file", createReadStream("./someFile.png"));
const postHeaders = {
headers: {
Authorization: "Bearer " + env("APY_KEY"),
...form.getHeaders(),
},
data: form,
};
axios.post("https://second-server.com/api", form, postHeaders)
.then((response) => {
console.log(JSON.stringify(response.data));
})
This code works, but I think it's not the right way to do this, since it writes the retrieved file into the local disc before posting it again into the second server. I need to be able to upload the file without writing it into the local disc. Is there any way?
Just replace form.append("file", createReadStream("./someFile.png")); with
form.append("file", response.data);
Both response.data and createReadStream("./someFile.png") are readable stream.
Note: You can directly transfer returned stream data without any need to create temporary file.
const axios = require("axios");
const FormData = require("form-data");
axios({
url: "http://localhost:3000/temp.png",
method: "GET",
responseType: "stream",
}).then(response => {
response.data.on("data", function(data) {
const form = new FormData();
form.append("file", data);
const postHeaders = {
headers: {
// Authorization: "Bearer " + env("APY_KEY"),
...form.getHeaders(),
},
data: form,
};
axios.post("http://localhost:8000/api", form, postHeaders)
.then((response) => {
// console.log(JSON.stringify(response.data));
})
.catch(function(error){
console.log(error)
});
});
})
.catch(function(error){
console.log(error)
});
I am able to succesfully upload a blob with proper contents from my web browser, but when I do it from react-native, the upload file is empty. Here is the code:
async function doit() {
const data = new FormData();
data.append('str', 'strvalue');
data.append(
'f',
new File(['foo'], 'foo.txt', {type: 'text/plain'}),
);
await fetch('http://localhost:3002/upload', {
method: 'POST',
body: data
});
}
However doing this same code from react-native, it uploads, but the file is empty.
Here is the node.js server I am using to test this. Loading http://localhost:3002 gives you a button called "upload it". Clicking it does the upload from the web. Screenshots of results are below.
var multiparty = require('multiparty');
var http = require('http');
http
.createServer(function (req, res) {
if (req.url === '/upload' && req.method === 'POST') {
console.log('multipart here');
var form = new multiparty.Form();
form.parse(req, function (err, fields, files) {
console.log(require('util').inspect({ fields, files }, false, null, true));
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ bar: true }));
});
return;
}
console.log('here');
// show a file upload form
res.writeHead(200, { 'content-type': 'text/html' });
res.end(
`
<script>
async function doit() {
const data = new FormData();
data.append('str', 'strvalue');
data.append(
'f',
// new File([new Blob(['asdf'], {type : 'text/plain'})], 'filename.txt'),
new File(['foo', 'what', 'the', 'hell'], 'foo.txt', {type: 'text/plain'}),
);
const res = await fetch('http://localhost:3002/upload', {
method: 'POST',
body: data
});
console.log(JSON.stringify(res, null, 4));
}
document.addEventListener('DOMContentLoaded', () => {
document.getElementById('b').addEventListener('click', doit, false)
}, false);
</script>
<button type="button" id="b">upload it</button>
`
);
})
.listen(3002);
From web browser we see the node server logs this, notice file size is 14.
However from react-native we see file size is 0:
I faced the same problem recently while posting an image from a react-native app to a server. However, I was able to make it work by appending the name and type of the file to the formData instance.
Here, the uri argument to uploadImageAsync is passed as a route parameter from the previous screen.
const postShoutHandler = async () => {
setShoutUploadStatus("Started Upload");
const response = await uploadImageAsync(route.params.captures);
const uploadResult = await response.json();
if (uploadResult === "Upload successful") {
setShoutUploadStatus("Success");
navigation.navigate("Home");
} else {
setShoutUploadStatus("Failed");
}
};
/* <--Upload image function --> */
const uploadImageAsync = (uri: string) => {
const apiUrl = "https://www.yourserver.com/image";
let uriParts = uri.split(".");
let fileType = uriParts[uriParts.length - 1];
let formData = new FormData();
formData.append("img", {
uri,
name: `photo.${fileType}`,
type: `image/${fileType}`,
});
formData.append("description", "HEY");
let options = {
method: "POST",
body: formData,
headers: {
Accept: "application/json",
"Content-Type": "multipart/form-data",
Authorization: "Bearer " + accessToken,
},
};
return fetch(apiUrl, options);
};
/* <--Upload image function --> */
Here is the Image configuration.
const photoData = await camera.takePictureAsync({
base64: true,
exif: false,
});
Redux Code
export const uploadImage = data => async dispatch => {
const config = {
headers: {
"Content-Type": "multipart/form-data"
}
};
try {
const res = await axios.post("/api/profile/upload", data, config);
// const res = await axios.post("/api/profile/upload", data, {
// headers: {
// "Content-Type": "multipart/form-data"
// }
// });
console.log(res);
dispatch({
type: AVATAR_UPLOAD,
payload: res.data
});
} catch (err) {
const errors = err.response.data.errors;
if (errors) {
errors.forEach(error => dispatch(setAlert(error.msg, "danger")));
}
dispatch({
type: PROFILE_ERROR,
payload: { msg: err.response.statusText, status: err.response.status }
});
}
};
React Code
const data = new FormData();
data.append("file", avatar);
uploadImage(data);
I get bad request message, req.files is empty
I try to upload file with Postman same configuration,it seems api works but can't upload with react formdata.
Any idea would be appreciated. Thanks in advance
try doing this:
const formData = new FormData();
formData.append('file', file);
const res = await axios.post("/api/profile/upload", formData, config);