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

22.9k Views Asked by At

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

   }
}
3

There are 3 best solutions below

1
On BEST ANSWER

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

0
On

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

      Axios
          .post('url', 
          
       formData 
          ,
            {
                "headers" :
                                { 

                                  "Content-Type":"multipart/form-data",
                                }
            }
          
          )

          .then( 

            res => {
                console.log(res.data)
                
              
               
              
              }

          )
           

And for the Input

<input style={{ display: 'none' }} accept="image/*" type="file" ref={fileInput}
onChange={e => setimagestudent(e.target.files)} />

0
On

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