Search code examples
javascriptreactjsfile-ioredux-form

File Input doesn't store file information, just the name


I'm using [email protected] and [email protected] and saving the data in a MongoDB collection. However, when I watch the file object that I uploaded in my Mongo DBs' collection it just retrieves the name of the file.

FileInput.js is the component that I pass to the redux-form Field component

FileInput.js

import React from 'react';

const handleChange = (handler) => ({target: {files}}) =>
  handler(files.length ? {file: files[0], name: files[0].name} : {});

export default ({
  input: {onChange, onBlur, value: omitValue, ...inputProps},
  meta: omitMeta,
  ...props
}) => (
  <input type="file"
    onChange={handleChange(onChange)} onBlur={handleChange(onBlur)}
    {...inputProps} {...props} />
);

And this is how I use it in my form

...
import FileInput from './FileInput';
...
<Field name="fileUploaded" component={FileInput} type="file" 
  />

And this is the document in the MongoDB collection

{...
"fileUploaded":{"name":"testingfile.png"},
...}

It seems it stores only the name of the file and I expect another key value pair with the file information/object in order to load and display this image/file later.


Solution

  • Redux-Form stores the file, perhaps you need to read it out and then send it as a multipart/form-data. The data should be accessible at state.form.myFormNameHere.values.mFieldNameHere.

    I made an ImageDisplay component that may be of help. It reads the file from a red-form file input and displays a preview.

    const ImageReader = ({ file }) => {
        const reader = new FileReader();
        const [imageUrl, setImageUrl] = useState('');
        if (file && file.file instanceof Blob) {
            reader.onload = (event) => {
                const { target: { result } } = event;
                setImageUrl(result);
            };
            reader.readAsDataURL(file.file);
            return <Image src={imageUrl} />;
        }
        return <Image src={null} />;
    };
    
    ImageReader.defaultProps = {
        file: null,
    };
    
    ImageReader.propTypes = {
        file: PropTypes.shape({
            name: PropTypes.string,
            file: PropTypes.any,
        }),
    };