【问题标题】:node.js / react Upload file with graphql createReadStream is not a functionnode.js / react 使用 graphql createReadStream 上传文件不是函数
【发布时间】:2021-07-12 06:36:18
【问题描述】:

我正在尝试将文件(图像)从我的客户端应用程序(react)发送到服务器(node.js)。 我收到错误消息:TypeError: createReadStream is not a function

这是我的代码:

graphql 架构:

  type File {
    filename: String!
    mimetype: String!
    enconding: String!
  }
  extend type Mutation {
    singleUpload(file: Upload!): File!
}

graphql 解析器:

module.exports = {
  Mutation: {
    async singleUpload(_, { file }) {
      try {
        const { createReadStream, filename } = await file;
        const stream = createReadStream();
        const pathName = path.join(__dirname, `/src/image/${filename}`);
        await stream.pipe(fs.createWriteStream(pathName));
        return file;
      } catch (err) {
        console.log(err);
        return err;
      }
    },
}

阿波罗服务器:

const apolloServer = new ApolloServer({
  typeDefs,
  resolvers,
  context,
  introspection: true,
  playground: {
    settings: {
      "schema.polling.enable": false,
      "editor.fontSize": 18,
    },
  },
});

应用客户端

const appClient = new ApolloClient({
  link: createUploadLink({ uri: baseURL + "/graphql" }),
  cache: new InMemoryCache(),
});

const SINGLE_UPLOAD = gql`
  mutation singleUpload($file: Upload!) {
    singleUpload(file: $file) {
      filename
      mimetype
      enconding
    }
  }
`;
const [userImage, setUserImage] = useState();

  const handleSubmit = (event: any) => {
    uploadFile({ variables: { file: userImage } });
}

在调试服务器中的文件对象时,它看起来像 C://fakeadress/name.jpg

你知道我为什么会收到这个错误吗?

我正在使用所有模块的最新版本。

【问题讨论】:

  • 没有发送文件,只有文件名?检查网络请求正文 - 对于上传它应该是表单数据编码,而不是通常的 json 查询+变量
  • 感谢您的回答。我认为这就是问题所在......

标签: node.js reactjs graphql fs


【解决方案1】:

我设法让它工作:

const [file, setFile] = useState({});
const [uploadFile] = useMutation(UploadMutation);

const handleSubmit = async () => {
    if (file) {
      uploadFile({
        variables: { file },
        // add the rest of the form fields to this query
        // refetchQueries: [{ query: FileQuery, variables: file }],
      });
      setFile({});
      // post message on form
      console.log("Uploaded successfully: ", file);
    } else {
      // return alertk
      console.log("No files to upload");
    }
  };

const { getRootProps, getInputProps } = useDropzone({
    accept: "image/*",
    onDrop: (acceptedFile) => {
      setFile(
        Object.assign(acceptedFile[0], {
          preview: URL.createObjectURL(acceptedFile[0]),
        })
      );
    },
  });

<div {...getRootProps({ className: "dropzone" })}>
                <input {...getInputProps()} />
                <p>Drag 'n' drop some file here, or click to select file</p>
              </div>

【讨论】:

  • 所以问题出在前端?后端代码没有错吗?
猜你喜欢
  • 1970-01-01
  • 2021-10-19
  • 2020-11-16
  • 2020-03-01
  • 1970-01-01
  • 2019-10-13
  • 1970-01-01
  • 2021-04-04
  • 2019-06-19
相关资源
最近更新 更多