从图像中获取blob并发送到服务器响应



通过编码学习反应,这里我想让用户选择一个图像,然后用户应该能够将其作为blob发送,需要将其转换为blob的建议吗?

这是fetchwithpost方法

const sendToserver = async () => {
let pollUrl = `api/...`;

const blob: any = await getImage();
// SEND THE BLOB TO YOUR SERVER
try {
const res = await fetch(pollUrl, {
method: "POST",
body: blob,
});
const data = await res.text();
if (res.ok) console.log("SUCCESS", data);
else throw new Error(data);
} catch (e) {
console.error(e);
}}

我的上传者需要关于如何获得blob图像的建议:

const {useState} = React;
const blobFile= (file) => new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = (event) => {
resolve(event.target.result)
};
reader.readAsDataURL(file);
})
const App = () => {
const [blob, setBlob] = useState('')
const onChange = (file) => {

if(!file) {
setBlob('');
return;
}
blobFile(file)
.then(dataUri => {
setBlob(dataUri)
})

}
return <div>
<img width="200" height="200" src={blob} alt="avatar"/>
<input type="file" onChange={(event) => onChange(event.target.files[0] || null)} />
</div>
}

ReactDOM.render(
<App/>,
document.getElementById('root')
);
<script src="https://unpkg.com/react/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<div id="root"></div>

英语不是我的母语,所以可能有错误

除非你想在用户发送后立即在浏览器中显示此图像,否则你不必将其转换为Blob以便发送到服务器,你可以读取此文件并将POST直接发送到你的api,因此在你的api中你可以以你想要的方式处理此文件,如保存到磁盘或发送到一些云服务,如aws桶。

无论如何,我将向您展示两个示例,如何转换为Blob以及如何发送到服务器。

转换为Blob

const onChange = (file) => {
if(!file) {
setBlob('');
return;
}
// just use the URL.createObjectURL to convert to blob
setBlob(URL.createObjectURL(file))
}

在将文件转换为Blob时应该注意,因为它可能导致内存问题,所以当用户不再需要Blob时,可以通过以下方式将其从内存中删除:

URL.revokeObjectURL(blob)

发送文件到服务器

这与您之前所做的几乎相同,但是直接将文件设置在body

const sendToServer = async (file) => {
if(!file) return
try {
return await fetch('api/...', { method: 'POST', body: file }).then(res => {
console.log("SUCCESS", res.text())
})
} catch(error) {
console.log(error)
}
}
const App = () => {
return <div>
<img width="200" height="200" src={blob} alt="avatar"/>
<input type="file" onChange={async (event) => await sendToServer(event.target.files[0] || null)} />
</div>
}

更新:要使用按钮发送文件,您可以隐藏输入,并使用按钮从输入触发对话框,如下所示:

// I will be using the useRef hook, but you could do it with vanilla javascript as well
import React, { useRef} from 'react'
const App = () => {
const fileInputRef = useRef(null)
// this is the function that triggers the dialog box from the input
const openFileDialog = () => {
fileInputRef.current?.click()
}
return <div>
<img width="200" height="200" src={blob} alt="avatar"/>
// add hidden property and the ref to useRef hook
<input hidden ref={fileInputRef} type="file" onChange={async (event) => await sendToServer(event.target.files[0] || null)} />
// open the input's dialog on click
<button onClick={openFileDialog}> Upload file </button>
</div>
}

下面的代码使用ReactJs将文件对象转换为blob

import React, {useState} from "react;
const ConvertImageObjectToBlob = () => {
const [file, setFile] = useState("");
const convertToBlob =(e) => {
setFile(URL?.createObjectURL(e.target.files[0]));
}
console.log({file}) //the result will in blob format.
return (
<>
<form>
<div> 
<input type="file" onChange={convertToBlob}/> 
</div>
</form>
</>
)
}
default export ConvertImageObjectToBlob;

最新更新