react js 处理文件上传

IT技术 javascript reactjs
2021-04-05 19:03:08

我是react js 的新手。我想用 react js 异步上传图片假设我有这个代码

var FormBox = React.createClass({
  getInitialState: function () {
    return {
      photo: []
    }
  },
  pressButton: function () {
    var data = new FormData();
    data.append("photo", this.state.photo);
    // is this the correct way to get file data?
  },
  getPhoto: function (e) {
    this.setState({
      photo: e.target.files[0]
    })
  },
  render: function () {
    return (
      <form action='.' enctype="multipart/form-data">
        <input type='file'  onChange={this.getPhoto}/>
        <button onClick={this.pressButton}> Get it </button>
      </form>
    )
  }
})

ReactDOM.render(<FormBox />, document.getElementById('root'))

任何答案将不胜感激!

6个回答

你可以利用 FileReader

var FormBox = React.createClass({
          getInitialState: function () {
            return {
              file: '',
              imagePreviewUrl: ''
            }
          },
          pressButton: function () {
            e.preventDefault();
          // TODO: do something with -> this.state.file
          console.log('handle uploading-', this.state.file);
          },
          getPhoto: function (e) {
            e.preventDefault();

            let reader = new FileReader();
            let file = e.target.files[0];

            reader.onloadend = () => {
              this.setState({
                file: file,
                imagePreviewUrl: reader.result
              });
            }

            reader.readAsDataURL(file);
            
          },
          render: function () {
            let {imagePreviewUrl} = this.state;
            let imagePreview = null;
            if (imagePreviewUrl) {
              imagePreview = (<img src={imagePreviewUrl} />);
            } else {
              imagePreview = (<div className="previewText">Please select an Image for Preview</div>);
            }
            return (
              <div>
              <form action='.' enctype="multipart/form-data">
                <input type='file'  onChange={this.getPhoto}/>
                <button onClick={this.pressButton}> Get it </button>
              </form>
              <div className="imgPreview">
                {imagePreview}
              </div>
              </div>
            )
          }
        })
        
        ReactDOM.render(<FormBox />, document.getElementById('root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react-dom.min.js"></script>
<div id="root"></div>

你的回答很聪明。但我希望上传的 pdf 在上传时显示其拇指图像
2021-06-09 19:03:08

如果您打算使用 node 和 express 上传文件,那么您必须同时创建服务器和客户端。服务器有 api,客户端将使用它通过 axios 上传文件。

  • 服务器部分

首先,我们要放入 express、explicit-fileupload、cors 和 nodemon 四个包。运行以下命令来安装应用程序。

npm i express express-fileupload cors nodemon

现在在您最喜欢的代码编辑器中打开 fileupload 文件夹并创建一个名为 server.js 的全新文档。

// server.js
const express = require('express');
const fileUpload = require('express-fileupload');
const cors = require('cors')
const app = express();
// middle ware
app.use(express.static('public')); //to access the files in public folder
app.use(cors()); // it enables all cors requests
app.use(fileUpload());
// file upload api
app.post('/upload', (req, res) => {
    if (!req.files) {
        return res.status(500).send({ msg: "file is not found" })
    }
        // accessing the file
    const myFile = req.files.file;
    //  mv() method places the file inside public directory
    myFile.mv(`${__dirname}/public/${myFile.name}`, function (err) {
        if (err) {
            console.log(err)
            return res.status(500).send({ msg: "Error occured" });
        }
        // returing the response with file path and name
        return res.send({name: myFile.name, path: `/${myFile.name}`});
    });
})
app.listen(4500, () => {
    console.log('server is running at port 4500');
})

用于node server.js启动服务器运行。

  • 客户

在您最喜欢的代码编辑器上打开 react app 文件夹,并在 src 文件夹中创建一个名为 fileupload.js 的全新报告。现在上传以下代码。

// fileupload.js
import React, { useRef, useState } from 'react';
import axios from 'axios';
function FileUpload() {
    const [file, setFile] = useState(''); // storing the uploaded file    
    // storing the recived file from backend
    const [data, getFile] = useState({ name: "", path: "" });    
    const [progress, setProgess] = useState(0); // progess bar
    const el = useRef(); // accesing input element
    const handleChange = (e) => {
        setProgess(0)
        const file = e.target.files[0]; // accesing file
        console.log(file);
        setFile(file); // storing file
    }
    const uploadFile = () => {
        const formData = new FormData();        
        formData.append('file', file); // appending file
        axios.post('http://localhost:4500/upload', formData, {
            onUploadProgress: (ProgressEvent) => {
                let progress = Math.round(
                ProgressEvent.loaded / ProgressEvent.total * 100) + '%';
                setProgess(progress);
            }
        }).then(res => {
            console.log(res);
            getFile({ name: res.data.name,
                     path: 'http://localhost:4500' + res.data.path
                   })
        }).catch(err => console.log(err))}
    return (
        <div>
            <div className="file-upload">
                <input type="file" ref={el} onChange={handleChange} />                
                <div className="progessBar" style={{ width: progress }}>
                   {progress}
                </div>
                <button onClick={uploadFile} className="upbutton">                   
                    Upload
                </button>
            <hr />
            {/* displaying received video*/}
            {data.path && <video src={data.path} autoPlay controls />}
            </div>
        </div>
    );
}
export default FileUpload;

现在在 App.js 文件中导入 FileUpload 组件。

// App.js
import React from 'react';
import FileUpload from './fileupload';
import './App.css';
function App() {
  return (
    <div className="App">
      <FileUpload />
    </div >
  );
}
export default App;

通过运行启动react应用程序npm start

更多信息:React 文件上传演示

使用以下模块选择图像。
https://www.npmjs.com/package/react-image-uploader

然后,您可以使用 xhr 请求将图像上传到服务器。以下是示例代码。

var xhr  = new XMLHttpRequest();
xhr.onload = function (e) {
//your success code goes here
}
var formData = new FormData();
xhr.open("POST", url, true);
formData.append('file', fileData);
xhr.send(formData);

import axios from 'axios';
var FormBox = React.createClass({
  getInitialState: function () {
    return {
      photo: [],
      name : '',
      documents:[]
    }
  },
  pressButton: function () {
    var component = this
    var data = new FormData();
    data.append("photo", component.state.photo, component.state.name);
    var request = axios.post('http://localhost:3000/document', data)
        request.then(function(response){
    // you need to send data from server in response
          if(response.status == 200){
             console.log('saved in db')
             component.state.documents.push(response.data.documents)
             // pushed document data in documents array
           }
        })


  },
  getPhoto: function () {
    var uploadfile = document.getElementById(upload_doc).files[0]
    this.setState({
      photo: uploadfile, name : uploadfile.name
    })
  },
  render: function () {
    var documents = this.state.documents.map((doc)=>{
       return <div>
                <a href={doc.url}>{doc.name}</a>
                <img src={doc.photo} />
              </div>
    })
   // you can show your documents uploaded this way using map function
    return (
      <form action='.' enctype="multipart/form-data">
        <input type='file' id='upload_doc'  onChange={this.getPhoto}/>
        <button onClick={this.pressButton}> Get it </button>
        <span>{documents}</span>
        // this way you can see uploaded documents
      </form>
    )
  }
})

ReactDOM.render(<FormBox />, document.getElementById('root'))
您应该考虑添加对您提出的答案的解释。
2021-06-13 19:03:08

一种更简单的方法,使用 axios 节点模块axios-fileupload

npm install --save axios-fileupload

const axiosFileupload = require('axios-fileupload'); 
axiosFileupload(url,file);