reactjs 如何在React JS中上传图像?

63lcw9qa  于 2023-02-22  发布在  React
关注(0)|答案(6)|浏览(145)
<div className="mb-1">
     Image <span className="font-css top">*</span>
     <div className="">
         <input type="file" id="file-input" name="ImageStyle"/>
     </div>
</div>

这是我提供的片段,我是用来从react js中的设备挑选文件,使用这个我可以选择文件,该文件名也显示,以及我现在想要的是存储在S3或任何地方这个文件,并从那里得到它的URL,并使用fetch API调用POST到我的服务器.

0sgqnhkj

0sgqnhkj1#

import React, { useState } from "react";

const UploadAndDisplayImage = () => {

  const [selectedImage, setSelectedImage] = useState(null);

  return (
    <div>
      <h1>Upload and Display Image usign React Hook's</h1>

      {selectedImage && (
        <div>
          <img
            alt="not found"
            width={"250px"}
            src={URL.createObjectURL(selectedImage)}
          />
          <br />
          <button onClick={() => setSelectedImage(null)}>Remove</button>
        </div>
      )}

      <br />
      <br />
      
      <input
        type="file"
        name="myImage"
        onChange={(event) => {
          console.log(event.target.files[0]);
          setSelectedImage(event.target.files[0]);
        }}
      />
    </div>
  );
};

export default UploadAndDisplayImage;
qoefvg9y

qoefvg9y2#

上传图像从您的文件,并显示在您的网页上的React,你也可以得到的图像对象的状态时,我们选择的图像显示在网页上,你必须转换图像对象的对象使用URL.createObjectURL(fileObject)

import React, { Component } from "react";

class DisplayImage extends Component {
  constructor(props) {
    super(props);
    this.state = {
      image: null
    };

   // if we are using arrow function binding is not required
   //  this.onImageChange = this.onImageChange.bind(this);
  }

  onImageChange = event => {
    if (event.target.files && event.target.files[0]) {
      let img = event.target.files[0];
      this.setState({
        image: URL.createObjectURL(img)
      });
    }
  };

  render() {
    return (
      <div>
        <div>
          <div>
            <img src={this.state.image} />
            <h1>Select Image</h1>
            <input type="file" name="myImage" onChange={this.onImageChange} />
          </div>
        </div>
      </div>
    );
  }
}
export default DisplayImage;
lstz6jyr

lstz6jyr3#

如果你想上传图像并将其发布到API,那么你可以安装react-image-uploader,它会将图像保存到本地端口,并通过POST请求保存到数据库中。

ih99xse1

ih99xse14#

这个代码让你上传图片到服务器,后端代码是用nestjs写的,并显示将要上传的图片。我用过formdata

import React, { useEffect, useState } from "react";
function Product() {

    const { REACT_APP_REST } = process.env;

    const [file, setFile] = useState([]);

    const handleFile = event => {
        setFile(
            URL.createObjectURL(event.target.files[0])
        );
        const formData = new FormData();
        formData.append("fileupload", event.target.files[0]);

        fetch(REACT_APP_REST + "/product/upload", {
            method: 'POST',

            body: formData,
            dataType: "jsonp"
        })
    };
    return (
        <>
            <Container fluid>
                <Col md="4">
                    <Card className="card-user">
                        <img src={file} />
                        <Card.Body>
                            <Form.Group>
                                <label>IMAGE</label>
                                <Form.Control
                                    type="file"
                                    required="required"
                                    onChange={handleFile}
                                ></Form.Control>
                            </Form.Group>
                        </Card.Body>
                        <hr></hr>

                    </Card>
                </Col>
            </Container>
        </>
    );
}

export default Product;
vsmadaxz

vsmadaxz5#

使用react-uploady,您可以非常轻松地完成此操作:

import React from "react";
import Uploady from "@rpldy/uploady";
import UploadButton from "@rpldy/upload-button";
import UploadPreview from "@rpldy/upload-preview";

const filterBySize = (file) => {
  //filter out images larger than 5MB
  return file.size <= 5242880;
};

const App = () => (
  <Uploady
    destination={{ url: "my-server.com/upload" }}
    fileFilter={filterBySize}
    accept="image/*"
  >
    <UploadButton />
    <UploadPreview />   
  </Uploady>
);
rqdpfwrv

rqdpfwrv6#

无法在“URL”上执行“createObjectURL”:重载解析失败。

由于某种原因,我不能使用URL。createObjectURL(image)作为

const [image, setImage] = useState(null);
  const [imgURL, setImgURL] = useState();

<img src={URL.createObjectURL(image)}/>

所以我把URL保存在按钮点击方法的即时显示状态。这成功了!

setImgURL(URL.createObjectURL(image));

不幸的是,当我使用useEffect时,我仍然得到同样的错误。

useEffect(() => {
    setImgURL(URL.createObjectURL(image));
  }, [image]);

相关问题