'Fetch the image and display it with Authorization in react
I'm going to fetch an image from ASP.NET core 5 web API and display it in react (with Authorization) But I get the following error Error image
when I remove Authorize and open the photo in the browser, the photo is displayed correctly
This is my code in react :
import axios from "axios";
import React, { useEffect, useState } from "react";
import { Buffer } from "buffer";
const Test = () => {
const [source, setSource] = useState();
useEffect(async () => {
const API_URL =
process.env.REACT_APP_URL +
"/Images/testimg/94e51231-cab8-4c51-8ee5-15b0da3164a4.jpg";
const token = JSON.parse(localStorage.getItem("user")).token;
try {
const response = await axios.get(API_URL, {
headers: {
responseType: "arraybuffer",
Authorization: `Bearer ${token}`,
},
});
if (response) {
console.log(response);
var buffer = Buffer.from(response.data,"base64")
setSource(buffer);
}
} catch (error) {
console.log(error);
}
}, []);
console.log(source);
return (
<img
id="test-img"
src={`data:image/jpeg;charset=utf-8;base64,${source}`}
/>
);
};
export default Test;
And This is my code in ASP.NET core 5 web API:
[Route("testimg/{name}")]
[HttpGet]
[Authorize]
public IActionResult testimg(string name)
{
string curentPath = Directory.GetCurrentDirectory();
string fullPath = Path.Combine(curentPath, $"resources\\{name}");
var image = System.IO.File.OpenRead(fullPath);
return File(image, "image/jpeg");
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
