如何在react js中显示图像



我试图将image显示为BLOB,但它不起作用,也不显示图像。我正在获取一个图像,将其转换为BLOB。并显示在CCD_ 3标签中。但它并没有显示图像。为什么?我可以转换BLOB网址,但它没有显示为什么?

import "./styles.css";
import {useEffect, useState} from "react";
import axios from "axios";
export default function App() {
const [state, setState] = useState(null)
useEffect(async ()=>{
var res=await  axios({
method: 'get',
url: 'https://www.oracle.com/node/oce/storyhub/dev/api/v1.1/assets/CONT0AE22311201E4708BEC9FBEC9C7096D8/native',
responseType: 'stream'
})
if (res) {
console.log(res)
// const imgBlob = window.URL.createObjectURL(res);
var binaryData = [];
binaryData.push(res.data);
const imgBlob = window.URL.createObjectURL(new Blob(binaryData, {type: "image/png"}))
console.log(imgBlob)
setState(imgBlob);
} else {
resolve({});
}
},[])
return (
<div className="App">
<img src={state}/>
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}

您可以直接将URL用作src,而无需执行额外的步骤将其转换为blob。

const { useEffect, useState } = React;
function App() {
const src = "https://www.oracle.com/node/oce/storyhub/dev/api/v1.1/assets/CONT0AE22311201E4708BEC9FBEC9C7096D8/native";
return (
<div className="App">
<img src={src} />
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.21.1/axios.min.js" integrity="sha512-bZS47S7sPOxkjU/4Bt0zrhEtWx0y0CRkhEp8IckzK+ltifIIE9EMIMTuT/mEzoIMewUINruDBIR/jJnbguonqQ==" crossorigin="anonymous"></script>
<div id="root" />

使用blob最简单的选择是只使用responseType: 'blob'

const { useEffect, useState } = React;
function App() {
const [state, setState] = useState(null);
useEffect(() => {
axios({
method: "get",
url:  "https://www.oracle.com/node/oce/storyhub/dev/api/v1.1/assets/CONT0AE22311201E4708BEC9FBEC9C7096D8/native",
responseType: "blob",
}).then((res) => {
if (res) {
setState(window.URL.createObjectURL(res.data));
}
});
}, []);
return (
<div className="App">
<img src={state} />
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.21.1/axios.min.js" integrity="sha512-bZS47S7sPOxkjU/4Bt0zrhEtWx0y0CRkhEp8IckzK+ltifIIE9EMIMTuT/mEzoIMewUINruDBIR/jJnbguonqQ==" crossorigin="anonymous"></script>
<div id="root" />

相关内容

  • 没有找到相关文章

最新更新