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.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2023-01-21 11:00:00 +0000
Seen: 12 times
Last updated: Aug 28 '22
In SCSS, what is the method for grouping and reusing a set of classes and styles?
What is the method to distinguish the presence of a json field in an array using presto?
What is Nextflow for genomics in AWS?
What are the differences between TREEFROG, CROW, and the CPPCMS C++ framework?
What does "waiting for handler commit" mean in relation to the slow writes experienced in MySQL 8?
What is the best way to arrange the file structure for both the backend and frontend in MERN?