如何在React的Material UI简单输入上启用文件上传?


73

我正在创建一个简单的表单,以使用带有redux表单和材料ui的电子反应样板上传文件。

问题是我不知道如何创建输入文件字段,因为材料ui不支持上传文件输入。

关于如何实现这一目标的任何想法?


此链接包含有关如何执行此操作的代码kiranvj.com/blog/blog/file-upload-in-material-ui ,带有有效的codeandbox链接
kiranvj

Answers:


91

APIcomponent为此提供了。

<Button
  variant="contained"
  component="label"
>
  Upload File
  <input
    type="file"
    hidden
  />
</Button>

4
而不是使用,style={{ display: "none" }}您可以简单地输入hidden
Will59 '20

88

较新的MUI版本:

<input
  accept="image/*"
  className={classes.input}
  style={{ display: 'none' }}
  id="raised-button-file"
  multiple
  type="file"
/>
<label htmlFor="raised-button-file">
  <Button variant="raised" component="span" className={classes.button}>
    Upload
  </Button>
</label> 

4
谢谢,这是来自此处的示例,您还需要input: {display: 'none'} 为此元素添加样式 。
Alex Zamai

5
或者只是<input hidden>
olefrank '18

4
您好-上传文件后(即,当您突出显示一个文件并在弹出的表单上单击“打开”时)onChange<input />会调用上的一个事件,但target事件对象的属性(或中的任何属性)上没有我的文件我可以看到的事件对象)。该文件在哪里可用?
jboxxx

2
@jboxxx:文件将打开target.filesinput元素具有内置的files属性,该属性列出每个选定的文件)
sfletche

2
在最新版本variant="raised"中,不推荐使用[[text],“ outlined”,“ contained”]中的一种
Renan Borges

34

您需要用 组件,并添加值为'label'的containerElement属性...

<RaisedButton
   containerElement='label' // <-- Just add me!
   label='My Label'>
   <input type="file" />
</RaisedButton>

您可以在本GitHub问题中阅读有关它的更多信息。

编辑:更新2019。

检查@galki的底部答案

TLDR;

<input
  accept="image/*"
  className={classes.input}
  style={{ display: 'none' }}
  id="raised-button-file"
  multiple
  type="file"
/>
<label htmlFor="raised-button-file">
  <Button variant="raised" component="span" className={classes.button}>
    Upload
  </Button>
</label> 

2
但是如何使用该文件对象?HTML FileReader似乎不起作用:/考虑到,我用过<input type='file' onChange='handleFile'> handleFile = file => { .. }
Paulo,

2
如果您在2019年访问此内容,请在底部查看@galki的答案:D
Blundering Philosopher

23

这是一个使用IconButton通过v3.9.2捕获输入(照片/视频捕获)的示例:

import React, { Component, Fragment } from 'react';
import PropTypes from 'prop-types';

import { withStyles } from '@material-ui/core/styles';
import IconButton from '@material-ui/core/IconButton';
import PhotoCamera from '@material-ui/icons/PhotoCamera';
import Videocam from '@material-ui/icons/Videocam';

const styles = (theme) => ({
    input: {
        display: 'none'
    }
});

class MediaCapture extends Component {
    static propTypes = {
        classes: PropTypes.object.isRequired
    };

    state: {
        images: [],
        videos: []
    };

    handleCapture = ({ target }) => {
        const fileReader = new FileReader();
        const name = target.accept.includes('image') ? 'images' : 'videos';

        fileReader.readAsDataURL(target.files[0]);
        fileReader.onload = (e) => {
            this.setState((prevState) => ({
                [name]: [...prevState[name], e.target.result]
            }));
        };
    };

    render() {
        const { classes } = this.props;

        return (
            <Fragment>
                <input
                    accept="image/*"
                    className={classes.input}
                    id="icon-button-photo"
                    onChange={this.handleCapture}
                    type="file"
                />
                <label htmlFor="icon-button-photo">
                    <IconButton color="primary" component="span">
                        <PhotoCamera />
                    </IconButton>
                </label>

                <input
                    accept="video/*"
                    capture="camcorder"
                    className={classes.input}
                    id="icon-button-video"
                    onChange={this.handleCapture}
                    type="file"
                />
                <label htmlFor="icon-button-video">
                    <IconButton color="primary" component="span">
                        <Videocam />
                    </IconButton>
                </label>
            </Fragment>
        );
    }
}

export default withStyles(styles, { withTheme: true })(MediaCapture);

IconButton绝对需要component =“ span”,这就是我所缺少的!
Locutus

12

这对我来说很有效(“ @ material-ui / core”:“ ^ 4.3.1”):

    <Fragment>
        <input
          color="primary"
          accept="image/*"
          type="file"
          onChange={onChange}
          id="icon-button-file"
          style={{ display: 'none', }}
        />
        <label htmlFor="icon-button-file">
          <Button
            variant="contained"
            component="span"
            className={classes.button}
            size="large"
            color="primary"
          >
            <ImageIcon className={classes.extendedIcon} />
          </Button>
        </label>
      </Fragment>

1

与应有的内容相同,只是将按钮组件更改为标签

<form id='uploadForm'
      action='http://localhost:8000/upload'
      method='post'
      encType="multipart/form-data">
    <input type="file" id="sampleFile" style="display: none;" />
    <Button htmlFor="sampleFile" component="label" type={'submit'}>Upload</Button> 
</form>

1

您可以使用Material UI的Input和InputLabel组件。如果您使用它们来输入电子表格文件,这是一个示例。

import { Input, InputLabel } from "@material-ui/core";

const styles = {
  hidden: {
    display: "none",
  },
  importLabel: {
    color: "black",
  },
};

<InputLabel htmlFor="import-button" style={styles.importLabel}>
    <Input
        id="import-button"
        inputProps={{
          accept:
            ".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel",
        }}
        onChange={onInputChange}
        style={styles.hidden}
        type="file"
    />
    Import Spreadsheet
</InputLabel>

1

2020年11月

带有Material-UI和React Hooks

import * as React from "react";
import {
  Button,
  IconButton,
  Tooltip,
  makeStyles,
  Theme,
} from "@material-ui/core";
import { PhotoCamera } from "@material-ui/icons";

const useStyles = makeStyles((theme: Theme) => ({
  root: {
    "& > *": {
      margin: theme.spacing(1),
    },
  },
  input: {
    display: "none",
  },
  faceImage: {
    color: theme.palette.primary.light,
  },
}));

interface FormProps {
  saveFace: any; //(fileName:Blob) => Promise<void>, // callback taking a string and then dispatching a store actions
}

export const FaceForm: React.FunctionComponent<FormProps> = ({ saveFace }) => {

  const classes = useStyles();
  const [selectedFile, setSelectedFile] = React.useState(null);

  const handleCapture = ({ target }: any) => {
    setSelectedFile(target.files[0]);
  };

  const handleSubmit = () => {
    saveFace(selectedFile);
  };

  return (
    <>
      <input
        accept="image/jpeg"
        className={classes.input}
        id="faceImage"
        type="file"
        onChange={handleCapture}
      />
      <Tooltip title="Select Image">
        <label htmlFor="faceImage">
          <IconButton
            className={classes.faceImage}
            color="primary"
            aria-label="upload picture"
            component="span"
          >
            <PhotoCamera fontSize="large" />
          </IconButton>
        </label>
      </Tooltip>
      <label>{selectedFile ? selectedFile.name : "Select Image"}</label>. . .
      <Button onClick={() => handleSubmit()} color="primary">
        Save
      </Button>
    </>
  );
};


0

如果您使用的是React函数组件,并且不想使用标签或ID,也可以使用参考。

const uploadInputRef = useRef(null);

return (
  <Fragment>
    <input
      ref={uploadInputRef}
      type="file"
      accept="image/*"
      style={{ display: "none" }}
      onChange={onChange}
    />
    <Button
      onClick={() => uploadInputRef.current && uploadInputRef.current.click()}
      variant="contained"
    >
      Upload
    </Button>
  </Fragment>
);

0
<input type="file"
               id="fileUploadButton"
               style={{ display: 'none' }}
               onChange={onFileChange}
        />
        <label htmlFor={'fileUploadButton'}>
          <Button
            color="secondary"
            className={classes.btnUpload}
            variant="contained"
            component="span"
            startIcon={
              <SvgIcon fontSize="small">
                <UploadIcon />
              </SvgIcon>
            }
          >

            Upload
          </Button>
        </label>

确保Button具有component =“ span”,对我有帮助。


0

这里有个例子:

return (
    <Box alignItems='center' display='flex' justifyContent='center' flexDirection='column'>
      <Box>
        <input accept="image/*" id="upload-company-logo" type='file' hidden />
        <label htmlFor="upload-company-logo">
          <Button component="span" >
            <Paper elevation={5}>
              <Avatar src={formik.values.logo} className={classes.avatar} variant='rounded' />
            </Paper>
          </Button>
        </label>
      </Box>
    </Box>
  )

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.