Graph Api Video Publish to Facebook Page not Working - reactjs

I am trying to make an application that allows user to upload images and videos posts to the facebook page by uploading them to the application.
My access token and all other stuffs are working fine for uploading pictures, but not for videos.
const [file, setFile] = useState([]);
code for uploading picture (working)
const formData = new FormData();
formData.append("source", file)
axios.post("https://graph.facebook.com/<pageId>/photos?",
formData,
{
headers:
{
"Content-Type": "multipart/form-data",
"Authorization": "Bearer <access_token>"
}
}
).then(
(res) => {
if (res.data["id"]) {
alert("Upload Successfully")
}
}
).catch((err) => {
alert("Error communicating to server")
console.log(err)
})
code for uploading video (not working)
const formData = new FormData();
formData.append("file", file);
axios.post("https://graph-video.facebook.com/v16.0/<page_id>/videos",
formData,
{
headers:
{
"Content-Type": "multipart/form-data",
"Authorization": "Bearer <same_access_token>"
}
}
).then(
(res) => {
if (res.data["id"]) {
alert("Upload Successfully")
}
}
).catch((err) => {
alert("Error communicating to server")
console.log(err)
})
code for getting input
<input className="btn" type="file" accept="video/mp4,video/x-m4v,video/*"
onChange=
{
(e) => { handleChange(e) }
}
/>
<input className="btn" type="file" accept="image/png, image/jpeg"
onChange=
{
(e) => { handleChange(e) }
} />
const handleChange = (e) => {
setFile(e.target.files[0]);
}

Related

Send Multiple Data With Axios

I have a problem , my problem is when i send multiple data with axios , the image in formdata dosen't send , but when i send only the formdata it works , if any know how to send multiple data ins axios just give me what's the solution
const onSubmit = async (data) => {
if(loading) return ;
setLoading(true);
const formData = new FormData();
formData.append("image",image);
let details = {
name:data.name,
image:formData,
price:data.price,
description:convertToRaw(editorState.getCurrentContent()).blocks[0].text,
qty:data.qty,
promo:data.oldPrice,
categorie:data.categorie,
// images:[image,image2,image3,image4]
}
try{
let config = {
headers:{
authorization:"Authorization Token "+jwt,
"Accept": "application/json",
"Content-Type": "multipart/form-data",
}
}
await axios.post('../../api/products',details,config)
.then(res => console.log(res.data))
.then(setLoading(false))
.catch(err => console.log(err))
}catch(err){
console.log(err);
}
}
I would do something like this while uploading with images:
const onSubmit = async (data) => {
if(loading) return ;
setLoading(true);
const formData = new FormData();
formData.append("image",image);
let details = {
name:data.name,
price:data.price,
description:convertToRaw(editorState.getCurrentContent()).blocks[0].text,
qty:data.qty,
promo:data.oldPrice,
categorie:data.categorie
}
for (let key in details) {
formData.append(key, details[key]);
}
try{
let config = {
headers:{
authorization:"Authorization Token "+jwt,
"Content-Type": "multipart/form-data",
}
}
await axios.post('../../api/products',formData ,config)
.then(res => console.log(res.data))
.then(setLoading(false))
.catch(err => console.log(err))
}catch(err){
console.log(err);
}
}

Mulitple image add in react js

I am working on a project where I have one page where you should be able to add images. One by one it's worked perfectly. Now I want to make to be able to multiple add and upload. I don't want to use any library for image upload.
const onFileChange = (e) => {
const reader = new FileReader();
reader.onload = () => {
if (reader.readyState === 2) {
setPreview(reader.result);
}
};
reader.readAsDataURL(e.target.files[0]);
if (e.target.files[0]) {
setOver(true);
}
const copy = [...image];
copy.push(e.target.files[0]);
setImage([...copy]);
};
const onFileUpload = () => {
const formdata = new FormData();
image.forEach((elem) => {
formdata.append("data", elem);
});
formdata.append("id_grobnog_mjesta", Id);
addImage(formdata);
};
const addImage = async (data) => {
try {
setIsLoading(true);
const response = await apiRequest({
method: "post",
url: `spisak-srebrenica/upload`,
headers: {
Authorization: `Bearer ${token}`,
},
data,
});
if (response.data.success) {
getVictimImage();
}
setIsLoading(false);
setImage([]);
} catch (err) {
setIsLoading(false);
setImage([]);
}
};
Upload component :
<Upload>
<BiImageAdd size={50} opacity={0.5} />
<input type="file" onChange={onFileChange} />
<div className="items">
<p>Dodajte sliku</p>
<span className="format">PNG,JPG,GIF do 10MB</span>
</div>
</Upload>
add multiple attribute
<input type="file" id="files" name="files" multiple>
https://www.w3schools.com/tags/att_input_multiple.asp

Cannot save image with multer and react

I'm trying to send some string and an image to my db from a form in React component. Everything is saved, also the image name, but the file is not in the pubblic/images folder. My req.file is alway undefined and my data always an empty object
This is the Multer middleware
//Multer
const path = require("path");
const multer = require("multer");
const store = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, "public/images");
},
filename: function (req, file, cb) {
cb(null, Date.now() + path.extname(file.originalname));
},
});
//Upload parameters
const upload = multer({
storage: store,
});
this is the post request of node
router.post("/", upload.single("image"), verify, async (req, res, next) => {
console.log(req.file);
const book = new Book({
title: req.body.title,
author: req.body.author,
image: req.body.image,
});
try {
const savedBook = await book.save();
res.send(savedBook);
} catch (error) {
res.send(error);
}
});
React
const token = useSelector((state) => state.token.token);
const data = new FormData();
//set Cover on change
const onChange = (e) => {
console.log(e.target);
data.append("image", e.target.files[0]);
console.log(data);
};
//Post Register
const Submit = async (e) => {
e.preventDefault();
await axios
.post(
"http://localhost:3000/api/book",
{
title: titleInput,
author: authorInput,
image: data,
},
{
headers: {
"auth-token": token,
},
}
)
.then((res) => {
console.log(res);
console.log(data);
})
.catch((error) => {
// handle error
console.log(error);
});
setAuthor("");
setTitle("");
};
Form
<form encType="multipart/form-data">
<input
type="text"
id="title"
value={titleInput}
name="title"
placeholder="title"
onChange={(e) => {
setTitle(e.target.value);
}}
/>
<input
type="text"
id="author"
value={authorInput}
name="author"
placeholder="Author"
onChange={(e) => {
setAuthor(e.target.value);
}}
/>
<input type="file" name="image" onChange={onChange} />
<button type="submit" onClick={Submit}>
Submit
</button>
</form>
Solved by changing the component code and sending data (create with Format()) to the node app.
//Post Register
const Submit = async (e) => {
e.preventDefault();
console.log(filename.name);
const data = new FormData();
data.append("author", authorInput);
data.append("title", titleInput);
data.append("image", filename);
data.append(
"imageTitle",
titleInput.split(" ").join("").toLowerCase() + ".jpg"
);
await axios
.post("http://localhost:3000/api/book", data, {
headers: {
"auth-token": token,
},
})
.then((res) => {
console.log(res);
})
.catch((error) => {
// handle error
console.log(error);
});
setAuthor("");
setTitle("");
};

Send images to backend using ReactJS

I want to make a post request to backend with all form data.
Uploading the images i get an array with data:
const normFile = e => {
const getFileList = e.fileList.map( i => i.originFileObj);
console.log('Upload event:', getFileList);
fetch('https:///uploadapi', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ images: getFileList })
})
.then(async response => {
const data = await response.json();
console.log(data, 'res data')
})
.catch(error => {
console.error('There was an error!', error);
});
if (Array.isArray(e)) {
return e;
}
return e && e.fileList;
};
Above is my code where i use Ant Design uploader.
But how to delete the File text before each object?
You have to use multipart/form-data header
Let's say you have an input
<input type="file" onChange={uploadFile}/>
And logical part:
uploadFile = (e) => {
const formData = new FormData();
formData.append('name_your_file', e.target.files[0])
fetch('https:///uploadapi', {
method: 'POST',
headers: { 'Content-Type': 'multipart/form-data' },
body: formData
})
}

React axios file upload failing - error "Multipart: Boundary not found"

My code isn't working as it should, it keeps receiving a 400 from the server and failing to upload. I must be making mistakes in the react component so please can you take a look for me? All's working in Postman, so the backend code seems fine.
import React, { useState } from "react";
import axios from "axios";
const UploadAvatar = () => {
const [image, setImage] = useState();
const handleUpload = async (e) => {
e.preventDefault();
const config = {
headers: {
"content-type": "multipart/form-data",
Authorization: localStorage.getItem("token"),
},
};
try {
const formData = new FormData();
formData.append("avatar", image);
const response = await axios.post(
"/users/me/avatar",
{ formData },
config
);
console.log(response);
} catch (err) {
console.error(err.message);
}
};
return (
<div>
<form onSubmit={handleUpload}>
Select image to upload:
<input
type="file"
onChange={(e) => setImage(e.target.value)}
name="fileToUpload"
/>
<input type="submit" value="Upload Image" name="submit" />
</form>
</div>
);
};
export default UploadAvatar;
There some things you need to do.
This is not related to the problem, but I think it is worth checking:
const config = {
headers: {
"content-type": "multipart/form-data",
Authorization: localStorage.getItem("token"),
},
}
What scheme is your Authorization (Basic, Bearer, OAuth)?
. If its a Bearer schema (e.g.), is your localStorage.getItem("token") returning only the token or is returning "Bearer {token}"? For bearer token, you need to include the word 'Bearer' before the token.
The content-type it's not really necessary here, but you can let it there if you prefer.
In your code, you need to do some changes:
In your handleUpload you need to do this:
try {
const formData = new FormData();
formData.append("avatar", image);
// I just removed the curly brackets from formData
const response = await api.post("/users/me/avatar", formData, config);
console.log(response);
} catch (err) {
console.error(err.message);
}
And in your input file type:
<input
type="file"
onChange={(e) => setImage(e.target.files[0])}
name="fileToUpload"
/>
For input file types, the target should be e.target.files, wich returns a list of files and each file is a FileList object. As you sending only one image you can set it as e.target.files[0] to get the first image.
And that´s all. It should work now! :)
I did a poc here and everything goes ok.
for bad request
it happens because of axios ,
your not sending json data
in your code
const response = await axios.post(
"/users/me/avatar",
{ formData },<---------here is the problem object
formData ,<-------try without curly brazes or use below detailed axios
config
);
console.log(response);
} catch (err) {
console.error(err.message);
}
};
change axios
axios({
method: 'post',
url: 'myurl',
data: formData ,
headers: {'Content-Type': 'multipart/form-data' }
})
.then(function (response) {
//handle success
console.log(response);
})
.catch(function (response) {
//handle error
console.log(response);
});
another problem
YOUR SENDING FILES
<input
type="file"
onChange={(e) => setImage(e.target.value)}<-------wrong e.target.files[0]
name="fileToUpload"
/>
change
if u sending mutliple files
e.target.files
or if you sending single file use
e.target.files[0]
change code
<input type="file"
onChange={(e) => setImage(e.target.files[0])}
name="fileToUpload"
/>

Resources