【问题标题】:Uploading a file with reactjs and dealing with C:/fakepath/file使用 reactjs 上传文件并处理 C:/fakepath/file
【发布时间】:2017-05-18 02:50:50
【问题描述】:

我有一个简单的表单来上传文件,稍后将处理我的后端 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>
       );

   }
}

【问题讨论】:

  • 为什么需要路径?
  • @epascarello 因为我必须在 Python 方面进行一些文件操作。所以我需要它的路径来打开、读取、写入任何内容。除非我不这样做,否则请告诉我如何
  • 但是 URL 与文件无关,这不是您访问文件详细信息的方式。您将文件错误地提交到服务器。见:stackoverflow.com/questions/2320069/jquery-ajax-file-upload

标签: javascript node.js file reactjs react-bootstrap


【解决方案1】:

如果你设置了var upload_file = this.state.value;,但你从未在状态对象中分配value,我不明白你为什么要这样做var upload_file = this.state.value;(在下面的示例中)。

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

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

Live Example

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

【讨论】:

  • 关于我的 upload_file 变量的事情是我在这里重写代码时犯的一个错误,因此它不会有数百行不相关和脱离上下文的东西。对此感到非常抱歉!我的错!无论如何,我不得不跳过几圈才能让它工作,但总的来说,这部分现在做得很好。谢谢!
【解决方案2】:

原因是因为您使用的是this.setState({value: e.target.value}),它只会使用 fakepath 字符串而不是实际的 DOM 元素来更新值。

我试图在 React 中上传一个文件,该文件将用作使用 fetch 的 GET 请求的主体。我的获取请求失败,因为正文有效负载是字符串“C:/fakepath/file”

这里是如何使用 useRef 和 useEffect 挂钩上传文件。在下面的示例中,我将文件传递给 API 请求的自定义钩子

export function App(){
    const [file, setFiles] = useState(null)
    const inputRef = useRef()

    useCustomFetchHook(file)

    return(
        <div>
            <input 
                type="file" id="input"
                // onChange={ e => setFiles(e.target.value)}
                onChange={() => setFiles(inputRef.current.files[0])}
                ref={inputRef}
            />
        </div>
    )
}

希望它有助于其他人在使用 React 上传文件时遇到“C:/fakepath/file”问题并遇到此 stackoverflow 帖子寻找解决方案

SM

【讨论】:

    【解决方案3】:

    const formData = new FormData(); formData.append("文件", imagestudent[0] );

          Axios
              .post('url', 
              
           formData 
              ,
                {
                    "headers" :
                                    { 
    
                                      "Content-Type":"multipart/form-data",
                                    }
                }
              
              )
    
              .then( 
    
                res => {
                    console.log(res.data)
                    
                  
                   
                  
                  }
    
              )
               
    

    对于输入

    onChange={e => setimagestudent(e.target.files)} />

    【讨论】:

      猜你喜欢
      • 2019-10-02
      • 1970-01-01
      • 1970-01-01
      • 2019-09-17
      • 1970-01-01
      • 2014-03-21
      • 2013-08-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多