Javascript 在反应中上传和读取文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46119987/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:20:24  来源:igfitidea点击:

Upload and read a file in react

javascriptreactjs

提问by ssss

Im trying to upload a file with React and see its contents, but what it gives me is C:\fakepath\. I know why it gives fakepath, but what is the correct way to upload and read the contents of a file in react?

我试图用 React 上传文件并查看其内容,但它给我的是C:\fakepath\. 我知道它为什么会给出fakepath,但是在 react 中上传和读取文件内容的正确方法是什么?

<input type="file"
      name="myFile"
      onChange={this.handleChange} />

handleChange: function(e) {
        switch (e.target.name) {
        case 'myFile':
            const data = new FormData();
            data.append('file', e.target.value);
            console.log(data);
        default:
            console.error('Error in handleChange()'); break;
        }
    },

回答by Purgatory

To get the file info you want to use event.target.fileswhich is an array of selected files. Each one of these can be easily uploaded via a FormDataobject. See below snippet for example:

要获取您要使用的文件信息,event.target.files它是一组选定文件。每一个都可以通过FormData对象轻松上传。例如,请参见下面的片段:

class FileInput extends React.Component {
    constructor(props) {
      super(props)
      this.uploadFile = this.uploadFile.bind(this);
    }
    
    uploadFile(event) {
        let file = event.target.files[0];
        console.log(file);
        
        if (file) {
          let data = new FormData();
          data.append('file', file);
          // axios.post('/files', data)...
        }
    }
    
    render() {
      return <span>
        <input type="file"
        name="myFile"
        onChange={this.uploadFile} />
      </span>
    }
}

ReactDOM.render(<FileInput />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react-dom.min.js"></script>
<div id="root"></div>

You may want to look into FileReaderwhich can help if you want to handle the file on the client side, for example to display an image.

FileReader如果您想在客户端处理文件,例如显示图像,您可能需要查看哪些可以提供帮助。

https://developer.mozilla.org/en-US/docs/Web/API/FileReader

https://developer.mozilla.org/en-US/docs/Web/API/FileReader

回答by Adam Falchetta

Try to use Multer and gridfs-storage on the back end and store the fileID along with your mongoose schema.

尝试在后端使用 Multer 和 gridfs-storage 并将 fileID 与您的猫鼬模式一起存储。

// Create a storage object with a given configuration
const storage = require('multer-gridfs-storage')({
  url: 'MONGOP DB ATLAS URL'
});

// Set multer storage engine to the newly created object
const upload = multer({ storage }).single('file');

router.post('/', upload, (req, res) => {

  const newreminder = new Reminders({
    category: req.body.category,
    name:req.body.name,
    type: req.body.type,
    exdate: req.body.exdate,
    location:req.body.location,
    notes:req.body.notes,
    fileID: req.file.id
  });
  newreminder.save(function(err){
    if(err){
      console.log(err);
      return;
    }

    res.json({ "success": "true"});
  });

});

Then on the front end treat it normally (with Axios) and upload the entire file and grab a hold of all the info in the normal react way:

然后在前端正常处理它(使用 Axios)并上传整个文件并以正常反应方式获取所有信息:

onSubmit = (e) => {
  e.preventDefault;
  const formData = new FormData();
  formData.append({ [e.target.name]: e.target.value })
  formData.append('file', e.target.files[0]);

  axios.post({
    method:'POST',
    url:'EXPRESS JS POST REQUEST PATH',
    data: formData,
    config:{ headers: {'Content-Type':'multipart/form-data, boundary=${form._boundary}'}}
  })
  .then(res => console.log(res))
  .catch(err => console.log('Error', err))
}

回答by Ariasa

Have you use dropzone ? see this react-dropzone

你用过 dropzone 吗?看到这个react-dropzone

easy implement, upload and return url if this important.

如果这很重要,请轻松实现,上传和返回网址。

onDrop: acceptedFiles => {
    const req = request.post('/upload');
    acceptedFiles.forEach(file => {
        req.attach(file.name, file);
    });
    req.end(callback);
}

回答by kylebebak

You can use React Dropzone Uploader, which gives you file previews (including image thumbnails) out of the box, and also handles uploads for you.

您可以使用React Dropzone Uploader,它为您提供开箱即用的文件预览(包括图像缩略图),并为您处理上传。

In your onChangeStatusprop you can react to the file's metadata and the fileitself, which means you can do any kind of client-side processing you want before or after uploading the file.

在您的onChangeStatus道具中,您可以对文件的meta数据及其file本身做出反应,这意味着您可以在上传文件之前或之后进行任何类型的客户端处理。

import 'react-dropzone-uploader/dist/styles.css'
import Dropzone from 'react-dropzone-uploader'

const Uploader = () => {  
  return (
    <Dropzone
      getUploadParams={() => ({ url: 'https://httpbin.org/post' })} // specify upload params and url for your files
      onChangeStatus={({ meta, file }, status) => { console.log(status, meta, file) }}
      onSubmit={(files) => { console.log(files.map(f => f.meta)) }}
      accept="image/*,audio/*,video/*"
    />
  )
}

Uploads have progress indicators, and they can be cancelled or restarted. The UI is fully customizable.

上传有进度指示器,可以取消或重新启动。用户界面是完全可定制的。

Full disclosure: I wrote this library.

完全披露:我写了这个库。