REACT : How can we Upload Image and Input text using Fetch or Axios in a single click function

落花浮王杯 提交于 2021-02-16 09:36:06

问题


So basically I'm new to react and couldn't find a single doc or resources regarding uploading an Image and input value at the same time.

One Solution is Form Data, But that isn't working as expected

The other method is Serialize, But I can't find any doc that explain the way to use in React

So, it would be really great for me and the newbies of React to know about this if you anyone could help me out.


回答1:


You can try the following method you can use multer with express to handle the file data that is been uploaded.

React file

import React, { Component } from "react";
import ReactDOM from "react-dom";
import axios from "axios";

class App extends Component {
  handleFileChange = e => {
    this.setState({ file: e.target.files[0] });
  };

  handleChange = e => {
    this.setState({ text: e.target.value });
  };

  upload = () => {
    if (this.state.file) {
      let data = new FormData();
      data.append("file", this.state.file);
      data.set("data", this.state.text);

      axios
        .post("http://yourhost/file", data)
        .then(response => console.log(response))
        .catch(error => console.log(error));
    }
  };

  render() {
    return (
      <div>
        <input type="text" onChange={this.handleChange} />
        <input type="file" onChange={this.handleFileChange} />
        <input type="button" onClick={this.upload} value="Upload" />
      </div>
    );
  }
}

export defaults App;

express server side

    const express = require('express');
    const app =express();
    const path = require('path');
    const cors = require('cors')();
    const bodyParser = require('body-parser');
    const multer  = require('multer')
    const port =process.env.PORT || 3000;;



    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({
       extended:true
    }));

    app.use(cors);

    const storage = multer.diskStorage({
      destination: __dirname +'/media/',
      filename(req, file, cb) {
       console.log(file);
       cb(null, `${file.originalname}-${new Date()}`);
      }
    });

    const upload = multer({ storage });

    app.post('/file',upload.single('file'), function(req, res) {
      console.log(req.body.data);
      console.log(req.files);
    });

   app.listen(port,()=> console.log('Running on port: '+port));


来源:https://stackoverflow.com/questions/55613586/react-how-can-we-upload-image-and-input-text-using-fetch-or-axios-in-a-single

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!