【问题标题】:How to Fetch and Display an Image from an express backend server to a React js frontend?如何从快速后端服务器获取和显示图像到 React js 前端?
【发布时间】:2020-01-09 18:36:46
【问题描述】:

我正在尝试从 express 后端获取图像并将它们显示在 react js 前端。我怎样才能完美地做到这一点?

我试图获取保存在名为“Backup”的后端文件夹中的图像,并在 react 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}`)
})

我希望图片会显示在用户页面中。 谢谢。

【问题讨论】:

  • 您的 res.data 是 Blob 吗?您收到了吗?
  • 我正在接收 blob,但它返回的图像大小小于实际文件大小
  • 将您的 blob 转换为文件 var file = new File( res.data, { type: "image/jpeg" } ); var imageUrl = URL.createObjectURL(文件);然后使用这个 imageUrl
  • @tarunkhosla 非常感谢.....它可以工作,但只需要一些我可以处理的简单修改......

标签: javascript node.js reactjs express axios


【解决方案1】:

这对我有用:

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

【讨论】:

    【解决方案2】:

    我使用 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}`)
    

    【讨论】:

      猜你喜欢
      • 2020-04-17
      • 1970-01-01
      • 1970-01-01
      • 2021-07-04
      • 2021-07-26
      • 2021-07-18
      • 2021-12-03
      • 1970-01-01
      • 2021-11-07
      相关资源
      最近更新 更多