Uploading a file with reactjs and dealing with C:/fakepath/file

13,611

Solution 1

I don't get why you do var upload_file = this.state.value; if you're setting var upload_file = this.state.value; but you never assign value in the state object (in the example below).

I think you are using the value property of the input['file'] instead of the files one. You have to take the selected file using the files property and use the FormData interface to map the form parameters.

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

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

Solution 2

The reason is because you're using this.setState({value: e.target.value}) which will only update the value with the fakepath string and not the actual DOM element.

I was trying to upload a file in React which will be used as a body for a GET request using fetch. My get request failed because body payload is a string "C:/fakepath/file"

Here is how to do upload a file using useRef and useEffect hooks. In below example, I pass the file to a custom hook for API request

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

Hope it's helpful for others facing "C:/fakepath/file" issue while uploading file using in React and come across this stackoverflow post looking for solution

SM

Share:
13,611
theJuls
Author by

theJuls

Some dev.

Updated on June 27, 2022

Comments

  • theJuls
    theJuls almost 2 years

    I have a simple form to upload a file which will later be dealt with my back-end python code. However, what I get when I attempt to upload the file is C:\fakepath\test.txt .

    From the research I did this is expected and done due to security concerns. Which is fine, but now my question is how in the world can I get around this to be able to use the file I am uploading on my back-end?

    I have looked a bunch of different places and none of them seem to address that.

    Here is my current code:

    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>
           );
    
       }
    }
    
  • theJuls
    theJuls over 7 years
    The thing about my upload_file variable was a mistake I made while rewriting my code here so it wouldn't have hundreds of lines of irrelevant and out-of-context stuff. So sorry about that! My bad! Anyway, I had to jump through a few hoops to make it work, but overall this part is now doing fine. Thanks!