简体   繁体   English

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

[英]getting blob from image and sending to server react

Learning react by coding, here i want to let user choose an image then user shoul be able to send it as blob, need advice on converting it into blob?通过编码学习反应,在这里我想让用户选择一个图像然后用户应该能够将它作为 blob 发送,需要关于将它转换为 blob 的建议吗?

this is my fetch with post method这是我用 post 方法获取的

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

my uploader which need advice on how to get blob image of it:我的上传者需要关于如何获取它的 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>

english is not my mother language, so could be mistakes英语不是我的母语,所以可能会出错

Unless you want to show this image to the user in the browser right after he sends it, you don't have to convert it to Blob in order to send to server, you can read this file and make a POST directly to your api, so there in your api you can handle this file the way you want, like saving to disk or sending to some cloud service like aws bucket.除非您想在用户发送此图像后立即在浏览器中显示此图像,否则您不必将其转换为 Blob 以发送到服务器,您可以读取此文件并直接向您的 api 进行POST ,因此,在您的 api 中,您可以按照您想要的方式处理此文件,例如保存到磁盘或发送到某些云服务(如 aws 存储桶)。

Anyway, I will show you both examples, how to convert to Blob and how to send to server.无论如何,我将向您展示这两个示例,如何转换为 Blob 以及如何发送到服务器。

converting to Blob转换为 Blob

const onChange = (file) => {

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

You should pay attention when converting files to Blob because it can leads to issues with memory, so when the Blob is no longer necessary for the user, you can remove it from memory this way:将文件转换为 Blob 时应注意,因为它可能会导致内存问题,因此当用户不再需要 Blob 时,可以通过以下方式将其从内存中删除:

URL.revokeObjectURL(blob)

sending the file to server将文件发送到服务器

it's almost the same thing you've did before, but with the file directly set in the 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>
}

Update: To use a button to send files you can make the input hidden and use the button to trigger the dialog box from the input, like so:更新:要使用按钮发送文件,您可以隐藏输入并使用按钮从输入触发对话框,如下所示:

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

Using ReactJs the code below converts a file object to a blob使用 ReactJs 下面的代码将文件 object 转换为 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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM