question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Handling file input

See original GitHub issue

Is there a way of handling a file input, whenever I try and do it I just get returned a C:/fakepath/... as the value. Am I missing something how do I access the file data

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Reactions:1
  • Comments:35 (5 by maintainers)

github_iconTop GitHub Comments

33reactions
jaredpalmercommented, Jul 10, 2017

@samjbmason

import * as React from 'react';

import { AxiosRequestConfig } from 'axios';
import Image from 'components/Image';
import { Progress } from 'components/Progress';
import ToasterInstance from '../Toast/ToasterInstance';
import { axios } from 'api/axios.config';
import { toApiError } from 'utils/api';

export interface MediaUploadProps {
  id: string;
  slug: string;
  value: string;
  onChange: (field: string, mediaId: string) => void;
}

export interface MediaUploadState {
  progress: number;
  file?: File;
  error?: string;
}

export class MediaUpload extends React.Component<
  MediaUploadProps,
  MediaUploadState
> {
  state: MediaUploadState = { progress: -1 };

  handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (!e.target.files) {
      return;
    }
    let file = e.target.files[0];
    this.setState({ file: file });

    let data = new FormData();
    data.append('file', file);

    let config: AxiosRequestConfig = {
      onUploadProgress: (p: any) => {
        this.setState({ progress: Math.round(p.loaded * 100 / p.total) });
      },
    };

    this.setState({ error: undefined, progress: 0 });

    axios.post('/v1/media?slug=' + this.props.slug, data, config).then(
      res => {
        this.setState({ error: undefined, progress: -1 });
        this.props.onChange(this.props.id, res.data.path);
      },
      err => {
        const message = toApiError(err);
        this.setState({ error: message, progress: -1 });
        ToasterInstance.show({
          message,
          iconName: 'danger',
          intent: 'danger',
        });
      }
    );
  }

  handleRemoveImage = () => {
    this.props.onChange(this.props.id, '');
  }

  render() {
    return (
      <div>
        <div>
          {this.props.value !== '' &&
            this.state.progress === -1 &&
            <Image path={this.props.value} size="lg" />}
          <div style={{ maxWidth: 144 }}>
            {this.state.progress > -1 &&
              <Progress percentage={this.state.progress} />}
          </div>
          {this.props.value &&
            <a
              style={{ marginTop: -40 }}
              className="button button--negative button--small button--secondary"
              role="button"
              onClick={this.handleRemoveImage}
            >
              Remove
            </a>}
        </div>
        <div style={{ marginTop: 10 }}>
          <label className="button button--purple button--secondary">
            Upload new picture
            <input
              className="visually-hidden"
              type="file"
              onChange={this.handleFileChange}
            />

          </label>
        </div>

      </div>
    );
  }
}
30reactions
rdsedmundocommented, Apr 14, 2019

I can’t understand why this and #247 got closed. Files are definitely not an edge case of forms, so such a common thing need to be handled by Formik natively properly.

For what it’s worth, redux-form handled it fine: https://github.com/erikras/redux-form/blob/e7ce5aec2bf0e24574e6f5f90bc04b9815c8e52e/src/events/getValue.js#L38

Read more comments on GitHub >

github_iconTop Results From Across the Web

Using files from web applications - Web APIs - MDN Web Docs
Using the File API, web content can ask the user to select local files and then read the contents of those files. This...
Read more >
How to Handle File Inputs With JavaScript | by John Au-Yeung
Use Hidden File Input Elements Using the click() Method ... We can trigger a file selection dialog to open with the click method...
Read more >
HTML input type="file" - W3Schools
The <input type="file"> defines a file-select field and a "Browse" button for file uploads. To define a file-select field that allows multiple files...
Read more >
C Files I/O: Opening, Reading, Writing and Closing a file
In this tutorial, you will learn about file handling in C. You will learn to handle standard I/O in C using fprintf(), fscanf(),...
Read more >
How to Use HTML5 Input Type 'file' - With Examples
The W3C HTML Standard defines several <input > types each designed to handle a specific type of data. For file uploading purposes, the...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found