Host images on imgbb sometimes showing error - reactjs

I upload images on one of reactjs project and host on imgbb but sometimes posting is working successfully and sometimes showing error.message: "Can't get target upload source info".
What's the problem actually ?
const [coverPhoto, setCoverPhoto] = useState([]);
const onChangeCover = (data) => {
setCoverPhoto(data)
const imgAPIKey = 'c83daa0cd70c09ca51b747864c4a22e1'
const image = data[0].file
const formData = new FormData()
formData.append('image', image)
const url = `https://api.imgbb.com/1/upload?key=${imgAPIKey}`
fetch(url,
{
method: "POST",
body: formData
})
.then(res => res.json())
.then(async result => {
console.log('imgbbCover', result)
const coverPhoto = result.data.url
await fetch(`http://localhost:5000/profiles/${email}`,
{
method: 'PUT',
headers: {
'content-type': 'application/json',
},
body: JSON.stringify({ coverPhoto })
})
})
}
see the console

Finally I've find a reason not posting the images properly sometimes is actually the freemium version has some limitations, one is not hosting every time properly...
Also tried the Cloudinary free hosting and found the same issue .

Related

React image upload not working through fetch

const submitData = (ev) => {
ev.preventDefault();
let formData = new FormData();
formData.append("topicName", topicName);
formData.append("topicMessage", topicMessage);
formData.append("pictures", pictures);
const requestOptions = {
method: "POST",
headers: {
"Content-Type": "multipart/form-data",
Accept: "application/json, text/plain, */*",
},
body: formData,
};
const sessionId = localStorage.getItem("sessionId");
let url = FormatUrl(`/api/v1/support/topic?sessionId=${sessionId}`);
fetch(url, requestOptions)
.then((res) => res.json())
.then((res) => {
ToastsStore.success(
"Ваше обращение отправлено, среднее ожидание ответа 6 часов"
);
})
.catch((error) => {
console.log(error);
});
};
Here i am sending data to upload file like this but no response getting back from Server.
Same things working in postman. Please refer to the screenshot.
Please take a look how can i fix it.
I've done some researches here.
I found this nice website: https://muffinman.io/blog/uploading-files-using-fetch-multipart-form-data/ .
Apparently you should try to remove the content-type header.
Though if it doesn't work, please inspect the network and share the request made on chrome / firefox. (F12 -> Network and then try your request)
Instead of appending data to the object like formData.append("topicName", topicName), use something like formData["topicName"] = topicName
This might solve your issue. Let me know if that helped.

Camunda: How to deploy a process using ReactJS fetch

I am trying to use Camunda's REST api to deploy a new process. However, I keep getting this HTTP response when my function is called.
Response:
{"type":"InvalidRequestException","message":"No deployment resources contained in the form upload."}
My jsx function
async deployNewProcess(xmlData) {
const formData = new FormData()
const blob = new Blob([xmlData], {type:'application/octet-stream'})
formData.append('upload', blob)
const response = await fetch(`${baseurl}/deployment/create`, {
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data; boundary=<calculated when request is sent>',
'Content-Length': '<calculated when request is sent>',
'Host': '<calculated when request is sent>'
},
body: formData
})
.then(result => console.log("SUCCESS: ", result))
.catch(err => console.log("ERROR: ", err))
}
Has anyone had any experience with this?
Based on this post https://camunda.com/blog/2018/02/custom-tasklist-examples/
see the example code
here:
https://github.com/camunda-consulting/code/blob/b2c6c3892d3d8130c0951a1d3584be7969fec82a/snippets/camunda-tasklist-examples/camunda-react-app/src/middleware/api.js#L11
and here:
https://github.com/camunda-consulting/code/blob/b2c6c3892d3d8130c0951a1d3584be7969fec82a/snippets/camunda-tasklist-examples/camunda-react-app/src/actions/camunda-rest/deployment.js#L4

React: Can't pass an id to an endpoint in order to display an image

I'm quite new to react and have an issue that i'm not sure whats wrong.
I have one external api with an endpoint that contains articles and another endpoint to get the images thats connected with the articles. I want to display the articles and the images together, but I can't get the images to show.
The flow is as follows:
First I find the article with the article api endpoint and the article id. And it looks like this:
const { itemId } = useParams()
const [article, setArticle] = useState([])
const [articleImg, setArticleImg] = useState('')
const [fileId, setFileId] = useState('')
useEffect(() => {
fetch(`https://api.fortnox.se/3/articles/${itemId}`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
'Access-Token': accessToken,
'Client-Secret': clientSecret
}
})
.then((res) => res.json())
.then((data) => {
console.log(data)
setArticle(data.Article)
console.log(data)
})
}, [itemId])
In order to get the image to that article I have to find a FileId by searching the article number against ArticleFileConnections endpoint:
(Documentation)
useEffect(() => {
fetch(`https://api.fortnox.se/3/articlefileconnections/?articlenumber=${itemId}`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
'Access-Token': accessToken,
'Client-Secret': clientSecret
}
})
.then((res) => res.json())
.then((data) => {
setFileId(data.ArticleFileConnections[0].FileId)
console.log(data.ArticleFileConnections[0].FileId) // Prints an id-number in the console
})
}, [])
When I have the FileId I use it with another endpoint called Archive in order to get the image. Documentation That fetch looks like this:
useEffect(() => {
fetch(`https://api.fortnox.se/3/archive/${fileId}`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
'Access-Token': accessToken,
'Client-Secret': clientSecret
}
})
.then((res) => res.json())
.then((data) => {
setArticleImg(data)
console.log(data) // Prints an object thats a folder structure with an empty array
})
}, [])
I tried to change the ${fileid} to the actual id-number in the archive endpoint like this
https://api.fortnox.se/3/archive/8c05c536-c110-402d-82da-60f25f6b0e1c Then I get this error message in the console:
Uncaught (in promise) SyntaxError: Unexpected token � in JSON at position 0
But I don't get that error if I pass the ${fileid} in the endpoint https://api.fortnox.se/3/archive/${fileid} Although when I console.log the state fileId that I pass in it prints the fileId-number.
So what I expect is that the fileId-state that I use in the archive endpoint should display an image by writing this code.
<div>
<img src={articleImg} alt="product" />
</div>
I hope all this is understandable and I hope someone can help me with what i'm doing wrong.
Thank you.
Note: It all works in postman. When I try the endpoints like the flow above it shows the image with this endpoint https://api.fortnox.se/3/archive/8c05c536-c110-402d-82da-60f25f6b0e1c
Your useEffect for fetching the fileId is behaving as a componentDidMount. What you want instead is a componentDidUpdate behavior, which you can do by
useEffect(() => {
fetch(`https://api.fortnox.se/3/archive/${fileId}`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
'Access-Token': accessToken,
'Client-Secret': clientSecret
}
})
.then((res) => res.json())
.then((data) => {
setArticleImg(data)
console.log(data) // Prints an object thats a folder structure with an empty array
})
}, [fileId]) // Notice the change here. It ensures that the useEffect is called every time the fileId is updated.

react-native upload image and data to api using axios

how to upload image to api using axios
i want to upload image with data to api using axios
i try with formdata but it did not work see below my code
and this is my code
uploadToServer= () => {
const file =this.state.photo
let formdata = new FormData()
formdata.append('sale_id', 1)
formdata.append('note_type_id', 4)
formdata.append('description', "test")
formdata.append('note_content_item', "test")
formdata.append('Note', file)
axios.post('api',
{data:formdata},{headers: {
'Content-Type' : 'multipart/form-data',
'Authorization':'xx'
}
})
.then(resp => console.log(resp))
.catch(error => console.error(error));
}
i try a lot of solution but it give me
Error: Request failed with status code 500
The 500 Internal Server Error is a very general HTTP status code that means something has gone wrong on the server.
You can request like this (using fetch):
let formdata = new FormData()
formdata.append('description', "test")
let i = {
uri: image.path,
type: 'multipart/form-data',
name: `image.jpg`,
};
formdata.append('image', i);
fetch(YourApi,{
method: 'post',
headers: {
'Content-Type': 'multipart/form-data',
},
body: formdata
}).then(response => {
response.text().then((res)=>{
console.warn(res)
})
}).catch(err => {
console.warn('error')
})

File upload using .fetch() in ReactJS

I am trying to upload file using .fetch() in ReactJS as Front End and Laravel as Back End. My ReactJS code is like below
update= (event) => {
let uploadImage = event.target.file;
let form = new FormData()
form.append('uploadImage',uploadImage)
fetch('http://127.0.0.1:8000/api/addresses/upload', {
headers: {
'Authorization': 'Bearer ' + Auth.getToken(),
'Content-Type': 'multipart/form-data',
},
method: "POST",
body: form,
})
.then(response => response.json())
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));
}
My Laravel code is like below
public function fileUpload(StoreImageRequest $request)
{
$image = $request->uploadImage;
$imagename = time() . $image->getClientOriginalName();
$destinationPath = public_path('/images');
$uploadValue = $image->move($destinationPath, $imagename);
if ($uploadValue) {
return response()->json($imagename);
}
}
I am getting error like below
and
Where is the issue ?
It's because you upload the image with form field name avatar, but in your Laravel method you access it with uploadImage.
So you can try change it to the following:
$request->avatar
Please checkout the Laravel Files documentation and make sure you follow their best practices.
I had the same issue. I fixed it by removing the content type.
Please check this article
https://upmostly.com/tutorials/upload-a-file-from-a-react-component

Resources