如何在多个上载反应js中获取文件输出?

时间:2019-04-13 03:36:57

标签: python reactjs flask

我尝试使用reactjs(客户端)并使用flask(服务器)创建多个上传图片,但是我遇到了一些问题,服务器中的输出文件只是[],

我已经尝试使用request.files.getlist(“ file []”)和request.get_json(force = True),但结果相同

这是我的代码:

客户端

import React, { Component } from "react";
import axios from 'axios';

class Menfess extends Component {
    constructor(props) {
    super(props);
    this.state = {
      files: [],
    };
    this._handleImageChange = this._handleImageChange.bind(this);
    this._handleSubmit = this._handleSubmit.bind(this);
  }

  _handleSubmit(e) {
    //Sumbit handler
    e.preventDefault();
    const formData = new FormData();
    formData.append('image', this.state.files,this.state.files.name);
    this.setState({files:FormData})
    console.log(this.state)
    axios
    .post('http://127.0.0.1:5000/postjson', formData,{headers: {
  'Content-Type': 'application/x-www-form-urlencoded'}}) 
    .then(response => { console.log(response) });
    this.setState({files:[]})
  }

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


  _handleImageChange(e) {
    e.preventDefault();

    let files = Array.from(e.target.files);

    files.forEach((file) => {
        let reader = new FileReader();
        reader.onloadend = () => {
            this.setState({    
                 files:[...this.state.files, file]
            });
        }
        reader.readAsDataURL(file);
    this.setState({files:[]})
    });
  }
//        <MDBInput name="text" label="Material input" value={this.state.text} onChange={this._handleChange}/>
  render() { 
    return (
      <div>
        <form onSubmit={this._handleSubmit} encType="multipart/form-data">
        <input className="upload" type="file" accept='image/*' onChange={this._handleImageChange} multiple/>
        <button type="submit" onClick={this._handleSubmit}>Upload Image</button>
        </form>
      </div>
    )
  }
}

export default Menfess;

服务器:

from flask import Flask
from flask import request
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

@app.route('/postjson', methods = ['POST'])
def postJsonHandler():
    #print (request.is_json)
    #content = request.get_json(force=True)
    files = request.files.getlist("file[]")        
    print(files)
    return 'JSON posted'

app.run()

有什么想法可以解决吗?谢谢

1 个答案:

答案 0 :(得分:0)

我首先想到的是为input字段提供一个name属性,例如filefile[](不同的约定适用于不同的服务器)。 / p>

此外,这可能与您有关-multiple files upload using same input name in django