简体   繁体   English

React Image上传Dropzone

[英]React Image upload Dropzone

I am in a bit of trouble. 我有点麻烦。 I am coding an image uploader with react, i created an upload component and i would like to get the preview image to show before i send it to the backend and upload it to a cdn. 我正在使用react编写图像上传器,我创建了一个上传组件,我希望在将其发送到后端并将其上传到cdn之前显示预览图像。 However, i cant manage to get the preview out from the state. 但是,我无法从州获得预览。 no errors, it just does not seem to get the preview prop from the state. 没有错误,它似乎没有从州获得预览道具。 would love to know your input. 很想知道你的意见。

Heres is my component 赫雷斯是我的组成部分

 import React, { PropTypes } from 'react' var Dropzone = require('react-dropzone'); import './uploader.scss' class Uploader extends React.Component { constructor(props){ super(props) this.state = { files: [] }; } onDrop(files) { console.log(files); let filename = files[0].name; let preview = files[0].preview; this.setState({ files: files, name: filename, preview: preview }); } render() { return ( <div className = 'dropzoneContainer' > <Dropzone ref={(node) => { this.dropzone = node; }} onDrop={this.onDrop} className= 'zone' multiple={false}> <div className = 'dropzone' >Upload Image</div> {this.state.files.preview ? <div> <img src={this.state.preview} /> </div> : null} </Dropzone> </div> ); } } export default Uploader 

I am using this react drag and drop library http://okonet.ru/react-dropzone/ 我正在使用这个反应拖放库http://okonet.ru/react-dropzone/

Thank you 谢谢

It's this bit of code: 这是一段代码:

{this.state.files.preview ? <div>
  <img src={this.state.preview} />
</div> : null}

You change this.state.files.preview to this.state.preview and you should be fine. 你将this.state.files.preview更改为this.state.preview ,你应该没问题。

Hope this helps! 希望这可以帮助!

Try 尝试

files.length == 0?
<Dropzone onDrop={this.onDrop.bind(this)}>
<p>Try dropping some files here, or click to select files to upload.
</p>
</Dropzone>
:<div>{files.map(f => <img src={f.preview} />)}</div> 

You can use React Dropzone Uploader , which gives you file previews out of the box, and also handles uploads for you. 您可以使用React Dropzone Uploader ,它可以为您提供开箱即用的文件预览,还可以为您处理上传。

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 totally customizable. 用户界面完全可以自定义。

Full disclosure: I wrote this library. 完全披露:我写了这个库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM