使用 reactjs 上传文件并处理 C:/fakepath/file

the*_*uls 4 javascript file node.js reactjs react-bootstrap

我有一个简单的表单来上传一个文件,稍后将处理我的后端 python 代码。但是,当我尝试上传文件时得到的是 C:\fakepath\test.txt 。

从我所做的研究来看,出于安全考虑,这是预料之中的。这很好,但现在我的问题是我到底如何才能解决这个问题才能使用我在后端上传的文件?

我看了很多不同的地方,似乎没有一个解决这个问题。

这是我当前的代码:

class SomeForm extends Component{

    handleFile(e){
        this.setState({value: e.target.value});
    }

    handleSubmit(e){
        var me=this;
        if (this.state.value.length>0){
            var upload_file = this.state.value;
            const request = axios.post(this.props.cfg_url+'/upload', {upload_file})
                .then(function(response){
                console.log('successfully uploaded', upload_file);
            })

        }
    }

   render(){
      return(


           <Form inline onSubmit={this.handleSubmit}>
                        <FormGroup controlId='uploadFormId'>
                            <ControlLabel>Upload File:</ControlLabel>
                            <FormControl
                                type='file'
                                label='File'
                                onChange={this.props.onChange}
                            />
                        </FormGroup>
                        <Button type='submit'>Upload</Button>
                    </Form>
       );

   }
}
Run Code Online (Sandbox Code Playgroud)

Ser*_*res 6

我不明白你为什么var upload_file = this.state.value;要设置var upload_file = this.state.value;但你从来没有value在状态对象中分配(在下面的例子中)。

我认为您正在使用的value属性input['file']而不是files一个。您必须使用files属性获取所选文件并使用FormData 接口来映射表单参数。

class SomeForm extends Component {

    handleSubmit(e){
        if (e.target.input.files.length) {
            const upload_file = e.target.input.files[0];
            const formData = new FormData();
            formData.append('file', upload_file);

            const request = axios.post(this.props.cfg_url+'/upload', formData)
                .then(function(response){
                    console.log('successfully uploaded', upload_file);
                });
        } else {
            console.log('You need to select a file');
        }
    }

    render(){
        return(
            <Form inline onSubmit={this.handleSubmit}>
                <FormGroup controlId='uploadFormId'>
                    <ControlLabel>Upload File:</ControlLabel>
                    <FormControl
                        type='file'
                        name="input-file"
                        label='File'
                    />
                </FormGroup>
                <Button type='submit'>Upload</Button>
            </Form>
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

现场示例

来源:https : //github.com/mzabriskie/axios/tree/master/examples/upload