admin管理员组文章数量:1312646
I'm trying to fetch images from an express backend and display them in the react js frontend. How can I achieve this perfectly?
I have tried to fetch the images saved in my backend folder named "Backup" and display them back to the user in the react js frontend. I have tried this using axios but still am getting an invalid image instead of the correct image.
Below is my fetch request in the frontend.
fetchImages = () => {
const imageName = 'garande.png'
const url = `http://localhost:5000/fetchImage/${imageName}`
axios.get(url, {responseType: 'blob'})
.then(res => {
return(
<img src={res.data} alt="trial" />
)
}
}
And this what I have in the server.js file in the backend
app.get('/fetchImage/:file(*)', (req, res) => {
let file = req.params.file;
let fileLocation = path.join('../Backup/images/', file);
//res.send({image: fileLocation});
res.sendFile(`${fileLocation}`)
})
I expect the Image to show up in the users page. Thanks.
I'm trying to fetch images from an express backend and display them in the react js frontend. How can I achieve this perfectly?
I have tried to fetch the images saved in my backend folder named "Backup" and display them back to the user in the react js frontend. I have tried this using axios but still am getting an invalid image instead of the correct image.
Below is my fetch request in the frontend.
fetchImages = () => {
const imageName = 'garande.png'
const url = `http://localhost:5000/fetchImage/${imageName}`
axios.get(url, {responseType: 'blob'})
.then(res => {
return(
<img src={res.data} alt="trial" />
)
}
}
And this what I have in the server.js file in the backend
app.get('/fetchImage/:file(*)', (req, res) => {
let file = req.params.file;
let fileLocation = path.join('../Backup/images/', file);
//res.send({image: fileLocation});
res.sendFile(`${fileLocation}`)
})
I expect the Image to show up in the users page. Thanks.
Share Improve this question asked Sep 6, 2019 at 23:30 GarandeGarande 1921 gold badge2 silver badges13 bronze badges 4- 1 Is your res.data a Blob and are you receiving it? – Tarun Khosla Commented Sep 6, 2019 at 23:37
- Am receiving the blob but it is returning an invalid image of whose size is less than the actual file size – Garande Commented Sep 7, 2019 at 9:20
- Convert your blob to File var file = new File( res.data, { type: "image/jpeg" } ); var imageUrl = URL.createObjectURL(file); Then use this imageUrl <img src={res.data} alt="trial" /> – Tarun Khosla Commented Sep 7, 2019 at 10:11
- @tarunkhosla Thank you so much ..... It works but only needs some simple modification which I can handle..... – Garande Commented Sep 9, 2019 at 14:16
3 Answers
Reset to default 3This worked for me:
export async function get(url: string) {
try {
const response = await fetch(url, {
method: 'GET', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
headers: {
'Content-Type': 'image/jpeg'
}
})
const blob = await response.blob()
return [URL.createObjectURL(blob), null];
}
catch (error) {
console.error(`get: error occurred ${error}`);
return [null, error]
}
}
function foo(props: any) {
const [screenShot, setScreenshot] = useState(undefined)
const url = props.url
useEffect(() => {
async function fetchData() {
// You can await here
const [response, error] = await get(url)
if (error)
log(error)
else {
log(`got response ${response}`)
setScreenshot(response)
}
}
fetchData();
}, [url])
return <div>
<img src={screenShot} className="Screenshot" alt="showing screen capture" />
</div>
}
I implemented a similar feature using useState():
If you are able to get the response as blob, try this in Frontend:
const [src, setSrc] = useState('');
fetchImages = () => {
const imageName = 'garande.png'
const url = `http://localhost:5000/fetchImage/${imageName}`
axios.get(url, {responseType: 'blob'})
.then(res => {
var imageUrl = URL.createObjectURL(res.data);
setSrc(imageUrl);
return(
<img src={src} alt="trial" />
)
}
}
You can also use
res.download
in backend:
res.download(`${fileLocation}`)
You do not need to create an API to access the image. Access your Image directly from the react frontend as follows:
<img src={'https://localhost:5000/Backup/images/garande.png'} alt="" />
Hope this solves your issue.
本文标签:
版权声明:本文标题:javascript - How to Fetch and Display an Image from an express backend server to a React js frontend? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741912010a2404499.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论