How can I read file content with react-dropzone?

六眼飞鱼酱① 提交于 2019-12-10 19:56:50

问题


I'm trying to learn more about working with files for an upcoming project. Is there a way with react-dropzone that I can run a function when onDrop happens to change the contents of the files I'm uploading? For example, if I'm uploading a word doc that says "Hi everybody" how would I change the content to "Hi Dr. Nick"?

I've tried just accessing the data by using the filereader api after before attempting to make the changes. I tried using filereader right after the opening curly bracket of the async function and wasn't able to get it to work.

import React from 'react';
import Dropzone from 'react-dropzone';
import { graphql } from 'react-apollo';
import gql from 'graphql-tag';

const FileUpload = ({
    children, disableClick, channelId, mutate, style = {},
}) => (
    <Dropzone
        style={style}
        className="ignore"
        onDrop={async ([file]) => {
            const response = await mutate({
                variables: {
                    channelId,
                    file,
                },
            });
            console.log(response);
        }}
        disableClick={disableClick}
    >
        {children}
    </Dropzone>
);

const createFileMessageMutation = gql`
  mutation($channelId: Int!, $file: File) {
    createMessage(channelId: $channelId, file: $file)
  }
`;

export default graphql(createFileMessageMutation)(FileUpload);

Any thoughts on how to access and modify the contents of the file are greatly appreciated! Thanks.


回答1:


onDrop={async ([file]) => {
  var reader = new FileReader();
  reader.onload = function(e) {
    var contents = e.target.result;
    displayContents(contents);
  };
  reader.readAsText(file);
}}

What you can do on frontend is to read file content and display it, all manipulations with file content should be done on server side. Push your file using ajax to your server with list of informations you want to change and use for example in nodeJS fs = require('fs')to make file modifications.

Also please visit this post i see that guys provided some solutions for your problem:

Is it possible to write data to file using only JavaScript?

and here is a fidlle taken from above link: http://jsfiddle.net/o4rhg1xe/1/

In Summary, you can read text file content using code i have provided and then use method from link to create Blob object with content you want and such file can be downlaoded by browser, (see fiddle)

Still in my opinion file modifications shoudl be moved to back-end side, ans i cant see no usecase to make them on frontend side.



来源:https://stackoverflow.com/questions/53880713/how-can-i-read-file-content-with-react-dropzone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!