如何使用 react-dropzone 读取文件内容?

How can I read file content with react-dropzone?

我正在尝试了解有关为即将开展的项目处理文件的更多信息。当 onDrop 碰巧更改我正在上传的文件的内容时,有没有一种方法可以使用 react-dropzone 运行 函数?例如,如果我正在上传一个写着 "Hi everybody" 的 word 文档,我该如何将内容更改为 "Hi Dr. Nick"?

在尝试进行更改之前,我尝试使用文件读取器 api 访问数据。我尝试在 async 函数的左大括号之后立即使用 filereader,但无法使其正常工作。

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);

非常感谢任何关于如何访问和修改文件内容的想法!谢谢

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

你在前端可以做的是读取文件内容并显示它,所有对文件内容的操作都应该在服务器端完成。使用 ajax 将您的文件推送到您的服务器,其中包含您要更改的信息列表,例如在 nodeJS 中使用 fs = require('fs') 进行文件修改。

另请访问此 post 我看到有人为您的问题提供了一些解决方案:

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

这是从上面 link 截取的小提琴:http://jsfiddle.net/o4rhg1xe/1/

总而言之,您可以使用我提供的代码读取文本文件内容,然后使用 link 中的方法创建包含您想要的内容的 Blob 对象,这样的文件可以通过浏览器下载,(请参阅 fiddle)

我仍然认为文件修改应该移至后端,而且我看不到在前端进行修改的用例。