Here is an example of how to upload a file using Apollo Server v4 and graphql-upload:
npm install graphql-upload
index.js
or server.js
file), import the GraphQLUpload
object from graphql-upload
package:const { GraphQLUpload } = require("graphql-upload");
GraphQLUpload
:const typeDefs = `
scalar Upload
type Mutation {
uploadFile(file: Upload!): String!
}
`;
uploadFile
mutation:const resolvers = {
Mutation: {
uploadFile: async (parent, { file }) => {
const { createReadStream, filename, mimetype } = await file;
const stream = createReadStream();
// Handle file stream
return `File ${filename} uploaded successfully`;
},
},
};
plugins
option that includes graphqlUploadExpress()
middleware:const { ApolloServer } = require("apollo-server-express");
const { graphqlUploadExpress } = require("graphql-upload");
const server = new ApolloServer({
typeDefs,
resolvers,
plugins: [graphqlUploadExpress()],
});
FormData
object to pass the file to your server:const fileInput = document.querySelector("#fileInput");
const formData = new FormData();
formData.append("file", fileInput.files[0]);
uploadFile
mutation with the formData
object:const response = await fetch("/graphql", {
method: "POST",
headers: { "Content-type": "application/json" },
body: JSON.stringify({
query: `
mutation uploadFile($file: Upload!) {
uploadFile(file: $file)
}
`,
variables: { file: formData.get("file") },
}),
});
const data = await response.json();
console.log(data);
That's it! You should now be able to upload files using Apollo Server v4 and graphql-upload.
Asked: 2023-01-21 11:00:00 +0000
Seen: 13 times
Last updated: Aug 28 '22