ReactJS Axios Image Request - javascript

I want make a request to API with headers having UserID:Pass
Example :
const config = {
headers: {
'X-RPC-DIRECTORY': 'main',
'X-RPC-AUTHORIZATION': 'userid:pass'
}
};
const res = await axios.get(`http://192.00.00.60:8000/obj/e1b8c19e-fe8c-43af-800c-c9400c0e90/abc.jpg`, config );
How can I render this?
Using the same I can get the image in Postman, But I want to render this into the page.

1- Create useState to save your base64 data.
const [base64, setBase64] = useState();
2- Create useEffect or function to transform image from get request to base64.
useEffect(() => {
axios
.get(
url,
{
responseType: "arraybuffer",
}
)
.then((response) =>
setBase64(Buffer.from(response.data, "binary").toString("base64"))
);
}, []);
3- Display the base64 data as image according to the syntax of the data URI scheme:
<img src={data:[<media type>][;charset=<character set>][;base64],<data>} />
example:
<img src={`data:image/jpeg;charset=utf-8;base64,${base64}`} />

axios({
method:'get',
url,
auth: {
username: 'xxxxxxxxxxxxx',
password: 'xxxxxxxxxxxxx'
}
})
.then((response) => {
//From here you can pass the response to local variable(state) and store/show image.
this.setState({ imageURL : response.data.image }); // change this as per your response
})
.catch((error) => {
console.log(error);
});
render(){
return(
<React.Fragment>
<img src={this.state.imageURL} alt="image" />
</React.Fragment>
)
}
Make sure you have right method type, URL and data is coming in response.

Got the Solution, as the response was content-type: blob so, what I did is to convert the blob to base64 from FileReader api and then display it.
const fileReaderInstance = new FileReader();
fileReaderInstance.readAsDataURL(blob);
fileReaderInstance.onload = () => {
base64data = fileReaderInstance.result;
console.log(base64data);
}

class Hello extends Component {
state = {
ulr: ''
}
componentDidMount() {
const config = {
headers: {
'X-RPC-DIRECTORY': 'main',
'X-RPC-AUTHORIZATION': 'userid:pass'
}
};
axios.get(`http://192.00.00.60:8000/obj/e1b8c19e-fe8c-43af-800c-c9400c0e90/abc.jpg`, config ).then((response) => {
this.setState({ url: response.data })
}).catch((error) => {
console.log(error)
})
}
render() {
return (
<>
<img src={this.state.url} alt="#" />
</>
)
}
}
export default Hello;
This should answer how to render the image after fetching the image from API.
But what i think is something is wrong withe URL.
i have few question:
Is the back-end API hosted on our own system?
Is the API publicly available because if it's not we cannot access it.
Have you set ant other headers or params that needs to be sent along the request.
I tried with postman also didn't get the image in response, it gave me error.

Related

issue accessing retrieved data from API which was pushed into a useState array - react ts

I am attempting to render data which was retrieved from my backend server.
The connection works fine and i'm able to retrieve a response.. My problem is that once I have loaded the information into my state-array, I cannot seem to access the properties within.
My useState array filled with the API request's data:
my backend's method i'm calling from my react program:
router.route("/api/issues").get(getAllIssues);
the route is calling the following function:
export const getAllIssues = async (
req: Request,
res: Response
): Promise<void> => {
try {
const issues: IssueInterface[] = await Issue.find({});
res.status(200).json({ issues });
} catch (err) {
throw err;
}
};
fetching the data from the api:
function Issues({ }: Props) {
const [issuesList, setIssuesList] = useState<IssueInterface[]>([]); // we retrieve from DB issues - we need it to look the same object's structure
useEffect(() => {
try {
axios({
method: 'get',
url: 'http://localhost:8001/api/issues',
headers: { 'Content-type': "application/json" }
}).then((response) => {
console.log(typeof (response))
const issuesStringified = JSON.stringify(response.data)
console.log("stringified: " + issuesStringified)
console.log(issuesList)
})
} catch (err) {
console.log("error : " + err);
}
}, [])
now my attempt to render parts of the array by using the following return function:
return (
<Stack>
<div>
{hasLoaded ? issuesList.map((issue: IssueInterface) => <div><h1>company: {issue.company_name}</h1></div>) : <></>}
</div>
</Stack>
)
provides the following outcome:
as if, it is unable to access the properties of each element.
any idea what am I doing wrong here?
regards! :_)

React render PDF file inside component based on API response

I have an APIs which returns File(byte[], "application/pdf") | byte[] from server.
In the frontend part, I create a request and can save this file like a pdf file to a computer, but I need to store this file(State or some other way) and render inside react component like PDF file, it's can be put on iframe or some another way(for me it's doesn't matter, just need render inside component after getting the file from API).
const instance = axios.create({
baseURL: process.env.REACT_APP_API_ROOT,
headers: {
"Content-Type": "application/json",
},
});
function getPdfByFileName(fileName: string): any {
return instance.get(`pdfs/${fileName}`);
}
function getPdfAsBlobByFileName(fileName: string): any {
return instance.get(`pdfs/${fileName}/array`);
}
useEffect(() => {
getPdfByFileName("fileName")
.then((response: AxiosResponse) => {
// const file = new Blob([response.data], { type: "application/pdf" }); // For API which returns blob
setPdf(response.data); // Need store file and correct render like PDF
})
.catch((err: AxiosError) => {
// process err
});
}
}, []);
return (
<div>
<iframe title="pdf" width="100%" height="600px" srcDoc={pdf}></iframe>
</div>
);
The result: Inside component I render the data but it's no PDF
I'm tryed:
use "Content-Type": "application/pdf" inside these requests.
Put the URL to file inside Iframe src attribute(it's works fine for
Anonymous but we have Bearer and need to secure the data).
Generate URL from blob API response and put to Iframe(not works).
Different pdf viewers, they work fine with physical PDF files based on the path to file but don't work in my case.
Thanks for any help.
For me the problem is on the axios, the response is not correct, I'm just switched to using fetch method and then this case start work correct for me, the same with axios does not work for me
const request = new Request(`URL_TO_API`,
{
method: "GET",
headers: {
Authorization: `Bearer ${accessToken}`,
},
mode: "cors",
cache: "default",
}
);
fetch(request)
.then((response) => response.blob())
.then((blob) => {
const file = window.URL.createObjectURL(blob);
const iframe = document.querySelector("iframe");
if (iframe?.src) iframe.src = file;
})
.catch((err: AxiosError) => {
// process error
});
return (
<div>
<iframe src="" width="100%" height="100%"></iframe>
</div>
);

CORS Error on uploading image/video file to google cloud in react js

When user drag and drop the Image, I need to call a method of the server to get the Media_id for that particluar image/video, in the response of that I am getting this ->
MAIN RESPONSE -->>
{
"status": 1,
"media": {"media_id": 27, "media_type": 1, "media_file_name": "a9989aafcdf1482d8a0967a81b54b476_80a2d60394f15063bef4e44e1a4d83f3.png", "media_placeholder": null, "media_ext": "png"},
"upload":
{
"upload_url": "https://storage.googleapis.com/fnc-59aa2e6b-71552c9d-6441d628-951a8f6f/l.img/ori/a9989aafcdf1482d8a0967a81b54b476_80a2d60394f15063bef4e44e1a4d83f3.png?Expires=1603388214&GoogleAccessId=12345678-compute%40developer.gserviceaccount.com&Signature=UNt8nS3%2BJYiS4AuYdZ7Z2fvfDZ0fAKf8bSZbeRlHyhqxb5i6xjpqnqgR7JYp9Q3FgJItcYr%2BHDL90WiUpbMQi%2B4s0XNW683CaSoUChkRMjj1AvkH%2Be0u8%2Fw5VVIMF9j52bTFePWISTLvwQ1RlEdNPNkrpbcamTsJFyBVi89%2BIpXArsVlhvDzK55Zvj%2Fvzh00GgdNrH%2BRog8Q%2BkGITE8bW%2FxRpQ30OdMZLjpLtp%2FNg5KVotHrx6Bet7vidKymiJQ9BbwCxTRGzBdAITr2rsKTMGZJzfvEKnIczsoiY91Zmc3hjGzUD9OxHGR%2BiRdN%2F2FbotOIVR48RE%2BoAdIGIEfKlw%3D%3D",
"file_name": "a9989aafcdf1482d8a0967a81b54b476_80a2d60394f15063bef4e44e1a4d83f3.png",
"content_type": "image/png", "exp": "2020-10-22 17:36:54.447484"
}}
So, I need to hit this upload url which is coming from the response.Below is my file where I am hitting this as soon as user drop the image ->
UploadImage.js
await this.props.getFirstMediaId(postdata).then(res => {
if (res.value && res.value.status === 1) {
let media_idArr = this.state.media_id.concat(res.value.media.media_id)
this.setState({ media_id: media_idArr, mediaUrl: res.value.upload })
customStatus = 'done';
}
}) //First call to the server to get Media_id and the cloud **upload URL**
***** FOR THIS API RESPONSE, PLEASE SEE THE ABOVE MAIN RESPONSE *****
const getUploadParams = () => {
console.log(this.state.mediaUrl, ' -->>> this.state.mediaUrl')
if (this.state.mediaUrl !== null) {
console.log(' in get upload param.')
return this.props.postImageToCloud(this.state.mediaUrl).then(res => {
console.log(res, '===>> here is cloud res.')
})
.catch(err => {
console.log(' here is error cloud -->>> ', err)
})
}
}
Below is the file where the method actually call API ->
service.js
export const getFirstMediaId = (data) => {
return {
type: GET_FIRST_LISTING_MEDIA,
async payload() {
let response = await callAxios.post(SUBMIT_LISTING_FIRST_MEDIA, data);
return objectPath.get(response, 'data', []);
}
}
}
export const postImageToCloud = (url) => {
return {
type: PUT_MEDIA_TO_CLOUD,
async payload() {
let response = await axios.put(url.upload_url, {}, {
headers: {
'Content-Type': `${url.content_type}`
}
})
return objectPath.get(response, 'data', []);
}
}
}
So, the first call is success and I got the above MAIN RESPONSE but as soon as it completes, I call the cloud PUT request and got this CORS error ->
Access to XMLHttpRequest at 'https://storage.googleapis.com/fnc-59aa2e6b-71552c9d-6441d628-951a8f6f/l.img/ori/a9989aafcdf1482d8a0967a81b54b476_80a2d60394f15063bef4e44e1a4d83f3.png?Expires=1603388214&GoogleAccessId=123456789-compute%40developer.gserviceaccount.com&Signature=UNt8nS3%2BJYiS4AuYdZ7Z2fvfDZ0fAKf8bSZbeRlHyhqxb5i6xjpqnqgR7JYp9Q3FgJItcYr%2BHDL90WiUpbMQi%2B4s0XNW683CaSoUChkRMjj1AvkH%2Be0u8%2Fw5VVIMF9j52bTFePWISTLvwQ1RlEdNPNkrpbcamTsJFyBVi89%2BIpXArsVlhvDzK55Zvj%2Fvzh00GgdNrH%2BRog8Q%2BkGITE8bW%2FxRpQ30OdMZLjpLtp%2FNg5KVotHrx6Bet7vidKymiJQ9BbwCxTRGzBdAITr2rsKTMGZJzfvEKnIczsoiY91Zmc3hjGzUD9OxHGR%2BiRdN%2F2FbotOIVR48RE%2BoAdIGIEfKlw%3D%3D' from origin 'http://localhost:8000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Please suggest me anything for make it working.
Thanks.
Finally after lot of efforts I came to know that I have to pass the file in the body of PUT request, here ->
let response = await axios.put(url.upload_url, { **file here** }, {
headers: {
'Content-Type': `${url.content_type}`
}
})
But I tried passing the image file object simple the html file object using formData and passing as it is, still getting the same error. Then i started using
react-dropzone and converted the image file into the string buffer as one of the example in React-dropzone. I am going to paste here that example maybe it can help anyone. See below ->
import React, {useCallback} from 'react'
import {useDropzone} from 'react-dropzone'
function MyDropzone() {
const onDrop = useCallback((acceptedFiles) => {
acceptedFiles.forEach((file) => {
const reader = new FileReader()
reader.onabort = () => console.log('file reading was aborted')
reader.onerror = () => console.log('file reading has failed')
reader.onload = () => {
// Do whatever you want with the file contents
const binaryStr = reader.result
console.log(binaryStr)
*****PASS THIS (binaryStr) AS IN THE BODY OF PUT TO AXIOS****
}
reader.readAsArrayBuffer(file)
})
}, [])
const {getRootProps, getInputProps} = useDropzone({onDrop})
return (
<div {...getRootProps()}>
<input {...getInputProps()} />
<p>Drag 'n' drop some files here, or click to select files</p>
</div>
)
}
This is one of the Official examples of React-Dropzone, So I just pass that string buffer obj and finally It worked, no CORS issue nothing.
The Google Storage API does simply not accept requests initiated from a browser in another domain, so you won't be able to achieve this.
You should not call the API from a client but from your backend. Here is the list of the suggested libraries: https://cloud.google.com/storage/docs/reference/libraries?hl=fr
Note that JavaScript in a browser environment is not suggested (only Node.js is)

How to download buffer data file or blob file in react native?

I am trying to download file using axios in react native. I got a response as arrayBuffer that has init8Array, init16Array and unit8Array, then i convert whole response into unit8Array, but i am trying to convert that unit8Array into string file it show unexpected data that i could not understand.Help me to get rid from this problem. I also use react-native-fetch-blob.
Below are my responses :-
Here is my code :-
export const getDocumentDetail = (reference) => {
return async dispatch => {
getToken().then(token =>{
AxiosBase.get('/document/'+reference,{
responseType : 'arraybuffer',
headers : {
Authorization : 'Bearer '+token,
Accept : 'application/pdf'
}
})
.then(response => {
console.log('Data',response.data)
var bufferData = Buffer.from(response.data)
var string = new TextDecoder("utf-8").decode(bufferData);
console.log('Buffer : ',bufferData,string)
dispatch({
type : DOCUMENT_DETAIL,
documentDetail : response.data
})
})
.catch(error => {
console.log('Documents Error : ',error)
})
})
}
}

File upload using axios post with basic auth

I want to upload file to server using axios post request.
I'm using the input tag for file and onChange setting the state.
If I use headers: { "content-type": "multipart/form-data" }, in axios the code gives error 400.
And If I remove it the code works fine but sends empty array via POST.
import React, { Component } from "react";
import axios from "axios";
export default class Image extends Component {
state = {
image: null
};
handleFiles = e => {
this.setState({ image: e.target.files[0] });
};
handleUpload = () => {
var session_url = "https:/localhost:3000/wp-json/gf/v2/entries/";
const fd = new FormData();
fd.append("image", this.state.image);
var entries = {
form_id: "1",
15: fd
};
axios
.post(session_url, entries, {
headers: { "content-type": "multipart/form-data" },
withCredentials: true,
auth: {
username: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
password: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
}
})
.then(res => {
this.setState({ data: res.data });
console.log(res, "Authenticated");
})
.catch(function(error) {
console.log("Error on Authentication", error.message);
});
};
render() {
return (
<div>
<input type="file" onChange={this.handleFiles} />
<button onClick={this.handleUpload}>Upload</button>
</div>
);
}
}
Your data is broken
Pass Axios either a plain object or a FormData object. It can handle both.
It will not properly serialise a plain object where one of the property values is a FormData object.
const entries = new FormData();
fd.append("image", this.state.image);
fd.append("form_id": "1");
Your content type is broken
Do not manually set a Content-Type header. It will be generated (including the mandatory boundary parameter for multipart requests) from the FormData object.
Your server-side code might not support this
You need to ensure that your server-side code can handle a multi-part request.

Categories

Resources