我在 React with Typescript 中使用以下代码创建了一个 ImageUrl。它创建了一个 URL,但不显示图片图像。单击 URL(例如“http://localhost:3003/0b4de100-d8eb-49a7-b43a-e2147310abbe”)会出现以下错误。我怎样才能解决这个问题 ?
Error:
http://localhost:3003/0b4de100-d8eb-49a7-b43a-e2147310abbe 无法加载资源:服务器响应状态为 404(未找到)
Code:
const [photoURL, setPhotoUrl] = useState<string>('');
const pictureData = await getPatientAvatar(patientId);
const blob = new Blob([pictureData], { type: 'image/jpeg' });
const imageUrl = URL.createObjectURL(blob);
setPhotoUrl(imageUrl);
<img src={photoUrl} />
网络选项卡中的图片:
调用创建的URLURL.createObjectURL() https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL is a blob URL https://stackoverflow.com/q/30864573/438273和它的protocol https://developer.mozilla.org/en-US/docs/Web/API/URL/protocol总是blob:
.
您在问题中显示的 URL 不是使用该方法创建的 blob URL,因为它的协议是http:
.
我在下面的代码片段中包含了一个工作示例。它将根据图像 blob 数据创建一个对象 URL,然后将 URL 渲染为字符串,同时将其用作渲染实际图像的源。您可以使用代码作为模型来重现成功。
<style>.avatar { height: 150px; width: 150px; }</style>
<div id="root"></div><script src="https://cdn.jsdelivr.net/npm/[email protected] /cdn-cgi/l/email-protection/umd/react.development.js"></script><script src="https://cdn.jsdelivr.net/npm/[email protected] /cdn-cgi/l/email-protection/umd/react-dom.development.js"></script><script src="https://cdn.jsdelivr.net/npm/@babel/[email protected] /cdn-cgi/l/email-protection/babel.min.js"></script><script>Babel.registerPreset('tsx', {presets: [[Babel.availablePresets['typescript'], {allExtensions: true, isTSX: true}]]});</script>
<script type="text/babel" data-type="module" data-presets="tsx,react">
// This Stack Overflow snippet uses UMD modules
const {StrictMode, useEffect, useState} = React;
// Since the Stack Overflow code snippet doesn't have access to your server,
// here is a function for fetching your example image data as a blob
async function fetchImageBlob (): Promise<Blob> {
const response = await fetch('https://i.imgur.com/uSvshvJ.jpg');
if (!response.ok) throw new Error('Response not OK');
return response.blob();
}
function App (): React.ReactElement {
const [objUrl, setObjUrl] = useState<string | undefined>();
useEffect(() => void (async () => {
if (objUrl) return;
const blob = await fetchImageBlob();
const oUrl = URL.createObjectURL(blob);
setObjUrl(oUrl);
})(), [objUrl]);
return objUrl
? (
<div>
<pre><code>{objUrl}</code></pre>
<img className="avatar" src={objUrl}></img>
</div>
)
: (<div>Loading image...</div>);
}
const reactRoot = ReactDOM.createRoot(document.getElementById('root')!);
reactRoot.render(
<StrictMode>
<App />
</StrictMode>
);
</script>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)