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);
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
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.
I'm trying to parse the logged in user's photo on node.js using graph API and something is not correct about the generated base64, I've tried different combinations and the photo is always corrupt.
export async function getPhotofromMsGraph(
accessToken: string,
): Promise<string | undefined> {
const config = {
headers: {
Authorization: `Bearer ${accessToken}`,
ResponseType: 'arraybuffer',
},
};
return axios
.get(graphConfig.graphPhotoEndpoint, config)
.then((response) => {
const { data } = response;
if (data) {
var imageType = 'image/jpeg';
var imageBytes = Buffer.from(data).toString('base64');
var imageSrc = `data:${imageType};base64,${imageBytes}`;
return imageSrc;
}
return undefined;
})
.catch((error) => {
throw error;
});
}
I'm trying to save a uploaded file with other fields like 'title', 'description',.
I'm able to save data using postman but I'm not able to save data from Reacjs form with Redux.
This is how my backend received the data:
const department = req.body.department;
const title = req.body.title;
const description = req.body.description;
const file = req.files.file;
I can save from postman but not react form.
This is my react form:
<form onSubmit={(e) => onSubmit(e)} encType='multipart/form-data'> ... some fields ... </form/
This is my react state and submission form data:
const [file, setFile] = useState('');
const [filename, setFilename] = useState('Choose file...');
const [bodyData, setBodyData] = useState({
title: '',
department: '',
});
const { title, department } = bodyData;
const onChange = (e) =>
setBodyData({ ...bodyData, [e.target.name]: e.target.value });
This is my Redux
// Create document file for specific patient
export const addFile = (form, id) => async (dispatch) => {
console.log(form.bodyData);
try {
const config = {
headers: { 'Content-Type': 'application/json' },
};
const res = await axios.put(
`/api/document/file/${id}`,
(form.bodyData, form.formData),
config
);
dispatch({
type: ADD_DOCUMENT_FILE,
payload: res.data,
});
dispatch(setAlert('Successfully Uploaded Patient Document', 'success'));
} catch (err) {
const errors = err.response.data.errors;
if (errors) {
errors.forEach((error) => dispatch(setAlert(error.msg, 'danger')));
}
dispatch({
type: DOCUMENT_FILE_ERROR,
payload: { msg: err.response.statusText, status: err.response.status },
});
}
};
const onChangeFile = (e) => {
setFile(e.target.files[0]);
setFilename(e.target.files[0].name);
};
const onSubmit = async (e) => {
e.preventDefault();
const formData = new FormData();
formData.append('file', file);
const collect = { formData, bodyData };
addFile(collect, match.params.id);
};
It seems like you are somewhat confused about how to handle this form submission.
In your onSubmit function, you reference a variable file which isn't defined in that scope, also you return formData, bodyData but bodyData isn't defined, and formData and bodyData are synonyms for the same data, so I don't know why you need both.
Consider this question for an example solution: How to post a file from a form with Axios
Yes. Finally I figured it out.
I changed my submit to this code:
const onSubmit = async (e) => {
e.preventDefault();
const formData = new FormData();
formData.append('title', title);
formData.append('department', department);
formData.append('file', file);
addFile(formData, match.params.id);
};
and the Redux I changed to this code:
export const addFile = (formData, id) => async (dispatch) => {
// console.log(form.bodyData);
try {
const config = {
// headers: { 'Content-Type': 'multipart/form-data' },
headers: { 'Content-Type': 'application/json' },
};
const res = await axios.put(
`/api/document/file/${id}`,
// { title: form.bodyData.title, department: form.bodyData.department },
formData,
config
);
dispatch({
type: ADD_DOCUMENT_FILE,
payload: res.data,
});
dispatch(setAlert('Successfully Uploaded Patient Document', 'success'));
} catch (err) {
const errors = err.response.data.errors;
if (errors) {
errors.forEach((error) => dispatch(setAlert(error.msg, 'danger')));
}
dispatch({
type: DOCUMENT_FILE_ERROR,
payload: { msg: err.response.statusText, status: err.response.status },
});
}
};