反应:如何通过单击功能使用Fetch或Axios上传图像和输入文本 [英] REACT : How can we Upload Image and Input text using Fetch or Axios in a single click function

查看:26
本文介绍了反应:如何通过单击功能使用Fetch或Axios上传图像和输入文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,基本上,我是新来的反应者,无法找到有关同时上传图像和输入值的单个文档或资源.

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.

一种解决方案是 Form Data ,但这不能按预期工作

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

另一种方法是 Serialize ,但是我找不到任何文档来说明在React中的使用方式

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

所以,对于我和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.

推荐答案

您可以尝试以下方法,将multer与express结合使用来处理上传的文件数据.

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

反应文件

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;

表达服务器端

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

这篇关于反应:如何通过单击功能使用Fetch或Axios上传图像和输入文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆