簡體   English   中英

如何從快速后端服務器獲取圖像並將其顯示到 React js 前端?

[英]How to Fetch and Display an Image from an express backend server to a React js frontend?

我正在嘗試從 express 后端獲取圖像並將它們顯示在 react js 前端。 我怎樣才能完美地實現這一點?

我試圖獲取保存在名為“備份”的后端文件夾中的圖像,並將它們顯示回反應 js 前端的用戶。 我已經使用 axios 嘗試過此操作,但仍然得到無效圖像而不是正確圖像。

下面是我在前端的獲取請求。

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" />
        )
    }
}

這就是我在后端的 server.js 文件中所擁有的

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}`)
})

我希望圖像顯示在用戶頁面中。 謝謝。

這對我有用:

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>
}

我使用 useState() 實現了一個類似的功能:

如果您能夠以 blob 形式獲得響應,請在前端嘗試此操作:

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" />
    )
}

}

您還可以在后端使用res.download

res.download(`${fileLocation}`)

您無需創建 API 即可訪問圖像。 直接從反應前端訪問您的圖像,如下所示:

<img src={'https://localhost:5000/Backup/images/garande.png'} alt="" />

希望這能解決您的問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM