最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - I'm trying to convert a base64 encoded string to a image on my react file - Stack Overflow

programmeradmin2浏览0评论
import React, { useRef, useCallback, useState } from 'react'
import Webcam from "react-webcam"
import Modal from 'react-bootstrap/Modal'
import Button from 'react-bootstrap/Button'
import 'bootstrap/dist/css/bootstrap.min.css'
import axios from 'axios'
// import base64Img from 'base64-img'
const fs = require('fs')


function App() {
  const [show, setShow] = useState(false)

  const handleClose = () => {
    setShow(false)
  }

  const videoConstraints = {
    width: 1280,
    height: 720,
    facingMode: "user"
  }

  const webcamRef = useRef(null);

  const capture = useCallback(
    () => {
      const imageSrc = webcamRef.current.getScreenshot();
      // const capture = document.createElement('img')
      // capture.src = imageSrc
      // base64Img.img(imageSrc, '../images', '1', function(err, filepath) {
      //   if(err) console.error(err)
      // });
      fs.writeFile('../images/1.jpg', imageSrc, {
        encoding: 'base64'
      }, function(err){
        if(err) console.error(err)
      })
      console.log(imageSrc)

      const formData = new FormData();

      formData.append('images', imageSrc)

      axios.post('http://localhost:5000/login', formData,{
          headers: {
              'content-type': 'multipart/form-data'
          },
          mode: 'no-cors'
        })

    },
    [webcamRef]
  )
   const logIn = () => {
    setShow(true)
  }
  return (
    <div>
        <button style={{
          position: 'relative',
          left: '500px',
          top: '300px'}}
          onClick={logIn}>Log in</button>

          <Modal size="lg" show={show} onHide={handleClose}>
            <Modal.Header closeButton>
              <Modal.Title>Please take a photo</Modal.Title>
            </Modal.Header>

            <Modal.Body>
            <Webcam
        audio={false}
        height={550}
        ref={webcamRef}
        screenshotFormat="image/jpeg"
        width={750}
        videoConstraints={videoConstraints}
      />
            </Modal.Body>

            <Modal.Footer>
              <Button onClick={ handleClose } variant="secondary">Close</Button>
              <Button onClick={capture} variant="primary">Take a snap</Button>
            </Modal.Footer>
          </Modal>
    </div>
  );
}

export default App;

This raised an issue:

TypeError: fs.writeFile is not a function
(anonymous function)
  31 | // base64Img.img(imageSrc, '../images', '1', function(err, filepath) {
  32 | //   if(err) console.error(err)
  33 | // });
> 34 | fs.writeFile('../images/1.jpg', imageSrc, {
     | ^  35 |   encoding: 'base64'
  36 | }, function(err){
  37 |   if(err) console.error(err)

the error occurs because I'm interchanging react syntatic code with nodejs syntax. I have tried to use: base64Img which gives me this error:

TypeError: fs.existsSync is not a function
getExists
node_modules/file-system/file-system.js:30
  27 | }
  28 | 
  29 | function getExists(filepath) {
> 30 |   var exists = fs.existsSync(filepath);
  31 | 
  32 |   if (exists) {
  33 |     return filepath;
View piled
push../node_modules/file-system/file-system.js.exports.mkdir
node_modules/file-system/file-system.js:60
  57 |  * ```
  58 |  */
  59 | exports.mkdir = function(filepath, mode, callback) {
> 60 |   var root = getExists(filepath);
  61 |   var children  = path.relative(root, filepath);
  62 | 
  63 |   if (util.isFunction(mode)) {
View piled
push../node_modules/file-system/file-system.js.exports.writeFile
node_modules/file-system/file-system.js:131
  128 |   callback = result.callback;
  129 | 
  130 |   // Create dir first
> 131 |   exports.mkdir(dirname, function() {
  132 |     fs.writeFile(filename, data, options, callback);
  133 |   });
  134 | };
View piled
push../node_modules/base64-img/base64-img.js.exports.img
node_modules/base64-img/base64-img.js:98
   95 |   var result = img(data);
   96 |   var filepath = path.join(destpath, name + result.extname);
   97 | 
>  98 |   fs.writeFile(filepath, result.base64, { encoding: 'base64' }, function(err) {
   99 |     callback(err, filepath);
  100 |   });
  101 | };
View piled
(anonymous function)
/src/App.js:31
  28 | const imageSrc = webcamRef.current.getScreenshot();
  29 | // const capture = document.createElement('img')
  30 | // capture.src = imageSrc
> 31 | base64Img.img(imageSrc, '../images', '1', function(err, filepath) {
     | ^  32 |   if(err) console.error(err)
  33 | });
  34 | // fs.writeFile('../images/1.jpg', imageSrc, {

I've tested couple of ideas and i've looked up videos and information on youtube and google but i have not found any solution for this.

I'm confused as to what is happening. Please help me with suggestions and solutions. I would appreciate it

import React, { useRef, useCallback, useState } from 'react'
import Webcam from "react-webcam"
import Modal from 'react-bootstrap/Modal'
import Button from 'react-bootstrap/Button'
import 'bootstrap/dist/css/bootstrap.min.css'
import axios from 'axios'
// import base64Img from 'base64-img'
const fs = require('fs')


function App() {
  const [show, setShow] = useState(false)

  const handleClose = () => {
    setShow(false)
  }

  const videoConstraints = {
    width: 1280,
    height: 720,
    facingMode: "user"
  }

  const webcamRef = useRef(null);

  const capture = useCallback(
    () => {
      const imageSrc = webcamRef.current.getScreenshot();
      // const capture = document.createElement('img')
      // capture.src = imageSrc
      // base64Img.img(imageSrc, '../images', '1', function(err, filepath) {
      //   if(err) console.error(err)
      // });
      fs.writeFile('../images/1.jpg', imageSrc, {
        encoding: 'base64'
      }, function(err){
        if(err) console.error(err)
      })
      console.log(imageSrc)

      const formData = new FormData();

      formData.append('images', imageSrc)

      axios.post('http://localhost:5000/login', formData,{
          headers: {
              'content-type': 'multipart/form-data'
          },
          mode: 'no-cors'
        })

    },
    [webcamRef]
  )
   const logIn = () => {
    setShow(true)
  }
  return (
    <div>
        <button style={{
          position: 'relative',
          left: '500px',
          top: '300px'}}
          onClick={logIn}>Log in</button>

          <Modal size="lg" show={show} onHide={handleClose}>
            <Modal.Header closeButton>
              <Modal.Title>Please take a photo</Modal.Title>
            </Modal.Header>

            <Modal.Body>
            <Webcam
        audio={false}
        height={550}
        ref={webcamRef}
        screenshotFormat="image/jpeg"
        width={750}
        videoConstraints={videoConstraints}
      />
            </Modal.Body>

            <Modal.Footer>
              <Button onClick={ handleClose } variant="secondary">Close</Button>
              <Button onClick={capture} variant="primary">Take a snap</Button>
            </Modal.Footer>
          </Modal>
    </div>
  );
}

export default App;

This raised an issue:

TypeError: fs.writeFile is not a function
(anonymous function)
  31 | // base64Img.img(imageSrc, '../images', '1', function(err, filepath) {
  32 | //   if(err) console.error(err)
  33 | // });
> 34 | fs.writeFile('../images/1.jpg', imageSrc, {
     | ^  35 |   encoding: 'base64'
  36 | }, function(err){
  37 |   if(err) console.error(err)

the error occurs because I'm interchanging react syntatic code with nodejs syntax. I have tried to use: base64Img which gives me this error:

TypeError: fs.existsSync is not a function
getExists
node_modules/file-system/file-system.js:30
  27 | }
  28 | 
  29 | function getExists(filepath) {
> 30 |   var exists = fs.existsSync(filepath);
  31 | 
  32 |   if (exists) {
  33 |     return filepath;
View piled
push../node_modules/file-system/file-system.js.exports.mkdir
node_modules/file-system/file-system.js:60
  57 |  * ```
  58 |  */
  59 | exports.mkdir = function(filepath, mode, callback) {
> 60 |   var root = getExists(filepath);
  61 |   var children  = path.relative(root, filepath);
  62 | 
  63 |   if (util.isFunction(mode)) {
View piled
push../node_modules/file-system/file-system.js.exports.writeFile
node_modules/file-system/file-system.js:131
  128 |   callback = result.callback;
  129 | 
  130 |   // Create dir first
> 131 |   exports.mkdir(dirname, function() {
  132 |     fs.writeFile(filename, data, options, callback);
  133 |   });
  134 | };
View piled
push../node_modules/base64-img/base64-img.js.exports.img
node_modules/base64-img/base64-img.js:98
   95 |   var result = img(data);
   96 |   var filepath = path.join(destpath, name + result.extname);
   97 | 
>  98 |   fs.writeFile(filepath, result.base64, { encoding: 'base64' }, function(err) {
   99 |     callback(err, filepath);
  100 |   });
  101 | };
View piled
(anonymous function)
/src/App.js:31
  28 | const imageSrc = webcamRef.current.getScreenshot();
  29 | // const capture = document.createElement('img')
  30 | // capture.src = imageSrc
> 31 | base64Img.img(imageSrc, '../images', '1', function(err, filepath) {
     | ^  32 |   if(err) console.error(err)
  33 | });
  34 | // fs.writeFile('../images/1.jpg', imageSrc, {

I've tested couple of ideas and i've looked up videos and information on youtube and google but i have not found any solution for this.

I'm confused as to what is happening. Please help me with suggestions and solutions. I would appreciate it

Share Improve this question asked May 17, 2020 at 20:10 Compression MonkeyCompression Monkey 211 gold badge1 silver badge8 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 1

You cannot use fs and writeFile in browser environment.

Instead, fetch the base64 which returns the blob. You append the blob to your formData.

Like this

const capture = useCallback(
    async () => {
      const imageSrc = webcamRef.current.getScreenshot();
      const blob = await fetch(imageSrc).then((res) => res.blob());
      const formData = new FormData();

      formData.append('images', blob)

      axios.post('http://localhost:5000/login', formData,{
          headers: {
              'content-type': 'multipart/form-data'
          },
          mode: 'no-cors'
        })
    },
    [webcamRef]
  )

See this

Also, the other option is to use Unit8Array and convert the base64 into blob

发布评论

评论列表(0)

  1. 暂无评论