2

I want to make a file uploader with react-dnd but i'm not able to get the content of a file, i can just get metadata about the file, like filename, size, etc.

This is the code of the React component where i want to drop the file:

import React from 'react';
import {
  DropTarget,
} from 'react-dnd';

import { NativeTypes } from 'react-dnd-html5-backend';

const style = {
    border: '1px solid gray',
    height: '15rem',
    width: '15rem',
    padding: '2rem',
    textAlign: 'center',
};

const spec = {
  drop(props, monitor){    
    console.log(monitor.getItem());
  }
};

const collect = (connect, monitor) => ({
  connectDropTarget: connect.dropTarget(),
});

class TargetBox extends React.Component {
  render() {
    const { connectDropTarget } = this.props;
    return connectDropTarget(
      <div style={style}>

      </div>
    );
  }
}

export default DropTarget(
  NativeTypes.FILE, 
  spec, 
  collect
)(TargetBox);

And here is the code that uses this component:

<DragDropContextProvider backend={HTML5Backend}>
    <TargetBox />
</DragDropContextProvider>

When i drop a file on the area of the TargetBox component the console.log on the drop function of the spec object only gives me the following info about the file:

lastModified: 1526416984630
lastModifiedDate: Tue May 15 2018 17:43:04 GMT-0300 (Brasilia Standard Time) {}
name: "product1.jpeg"
size: 14226
type: "image/jpeg"
webkitRelativePath: ""

But i want to retrieve the bytes of the file so i can send them to the server, is there a way to do this only using react-dnd?

krionz
  • 417
  • 1
  • 4
  • 15

1 Answers1

2

I just had to use the FileReader API. A FileReader object accepts a Blob, and the file that i receive on the drop method has the prototype of a Blob object. So i just had to change the drop method to the following code:

drop(props, monitor ){    
    const droppedImage = monitor.getItem().files[0];

    const reader = new FileReader();
    reader.onloadend = (e) => console.log(e);
    reader.onprogress = (e) => console.log(e);
    reader.readAsArrayBuffer(droppedImage);       
}
krionz
  • 417
  • 1
  • 4
  • 15