I am trying to upload files with Angular Apollo as Client and Apollo 2.0 as Server.
Trust me, I tried every tutorial, example I could find on the internet but no help. There's a library called apollo-upload-file they have given an example of how to implement it but at the client side they have used React. Although I tried implementing his example but nothing works.
Please help.
See graphql-upload docs for details. singleUpload(file: Upload!): File! // by the `graphql-upload` package. // Invoking the `createReadStream` will return a Readable Stream.
Most GraphQL implementations do provide provisions to implement File Uploads through your GraphQL API however. Fully-Featured: All GraphQL APIs will use a text-based response format, so file downloads will still require a separate endpoint. This means your file upload and download will become separated.
Altair supports uploading both single files and an array of files (by switching the file upload from single to multiple file mode, or using the dot notation in single file mode e.g. for an array named fileList , you define the files as fileList. 0 , fileList. 1 , fileList.
In your schema you need to define the file argument as type Upload this is a built in type provided by Apollo
const { gql } = require('apollo-server');
const TypeDef = gql `
type Mutation {
upload(file: Upload!)
}
`
If you are getting an error about type Upload not being a type you can also define it in your schema ( I had this issue )
const { gql } = require('apollo-server');
const TypeDef = gql `
scalar Upload
type Mutation {
upload(file: Upload!)
}
`
In your revolvers you can access the file in your args, One thing to note is that the file will be a promise;
const resolver = {
Mutation: {
async upload(obj, args, context, info) {
const file = await args.file;
// ... DO STUFF
},
}
}
In the client you need to use the apollo-angular-link-http
package to help with file uploads.
In the context
of the request use need to set useMultipart : true
Query will look something like this
const uploadFileMutation = gql`
mutation UploadMutation(
$file: Upload!
) {
upload(file: $file) {
YOUR RESPONSE
}
}
}
`
The Apollo request will look like this
constructor(
private Apollo: Apollo
) { }
fileUpload(file){
this.Apollo.mutate<any>({
mutation: uploadFileMutation,
variables: {
file: this.file
},
context: {
useMultipart: true
}
}).subscribe(({ data }) => {
this.response = data.upload
});
}
I hope this helps or at least gets you on the right track.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With