如何使用apollo-angular-graphql上传文件?求相关包及传输格式说明
Hey there! Let's break down your questions about file uploads with apollo-angular and GraphQL step by step:
1. How to implement file upload with apollo-angular-graphql
To get file uploads working, you'll need to set up both the client (with apollo-angular) and ensure your GraphQL server supports multipart file uploads. Here's a straightforward setup:
Step 1: Install required dependencies
First, add the core package that enables upload support for Apollo Client:
npm install apollo-upload-client graphql # If you haven't already installed apollo-angular, run this too: npm install apollo-angular @apollo/client/core
Step 2: Configure Apollo Client with upload support
Replace the default HTTP link with createUploadLink from apollo-upload-client—this handles wrapping files into the proper multipart request format:
// app.module.ts or your Apollo config file import { NgModule } from '@angular/core'; import { ApolloModule, APOLLO_OPTIONS } from 'apollo-angular'; import { ApolloClient, InMemoryCache } from '@apollo/client/core'; import { createUploadLink } from 'apollo-upload-client'; export function createApollo() { const client = new ApolloClient({ link: createUploadLink({ uri: '/graphql', // Replace with your actual GraphQL endpoint }), cache: new InMemoryCache(), }); return client; } @NgModule({ imports: [ApolloModule], providers: [ { provide: APOLLO_OPTIONS, useFactory: createApollo, }, ], }) export class GraphQLModule {}
Step 3: Create a file upload mutation
Define a GraphQL mutation that accepts an Upload type (this is a standard scalar for file uploads in GraphQL):
# upload-file.mutation.graphql mutation UploadFile($file: Upload!) { uploadFile(file: $file) { id filename mimetype url # The URL to access the uploaded file later } }
Step 4: Implement the upload logic in an Angular component
Use apollo-angular's mutate method to send the selected file to your server:
import { Component } from '@angular/core'; import { Apollo } from 'apollo-angular'; import gql from 'graphql-tag'; // Import the mutation we defined const UPLOAD_FILE = gql` mutation UploadFile($file: Upload!) { uploadFile(file: $file) { id filename mimetype url } } `; @Component({ selector: 'app-file-upload', template: ` <input type="file" (change)="handleFileSelect($event)" accept="image/*,application/pdf"> ` }) export class FileUploadComponent { constructor(private apollo: Apollo) {} handleFileSelect(event: Event): void { const fileInput = event.target as HTMLInputElement; const selectedFile = fileInput.files?.[0]; if (!selectedFile) return; // Send the file via GraphQL mutation this.apollo.mutate({ mutation: UPLOAD_FILE, variables: { file: selectedFile } }).subscribe({ next: (response) => { console.log('Upload successful! File details:', response.data); // You can store the returned URL to display/download the file later }, error: (err) => { console.error('Upload failed:', err); } }); } }
Note: Your server needs to support the GraphQL multipart request spec. For Node.js servers, use the graphql-upload package to handle incoming file uploads, process them (save to disk, cloud storage like S3, etc.), and return the file metadata/URL.
2. Toolkits for file uploads with apollo-angular + GraphQL mutation, plus upload/download formats
Recommended Toolkits
- apollo-upload-client: This is the official, most widely used package that integrates seamlessly with apollo-angular. It handles all the low-level multipart request formatting so you don't have to build it from scratch.
- ngx-file-drop (optional): If you want drag-and-drop file upload UI in your Angular app, this library works great alongside
apollo-upload-client—it just handles the UI part, while the GraphQL upload logic still uses the core apollo setup.
Upload & Download Formats
Upload Format
- Client-side:
apollo-upload-clientautomatically packages the file and GraphQL operation into amultipart/form-datarequest, which is the standard for GraphQL file uploads. TheUploadscalar in your mutation maps directly to the selectedFileobject from the input. - Server-side: When using
graphql-upload, the server receives the file as a streamable object with properties likefilename,mimetype,createReadStream()—you can use this stream to save the file to your storage solution.
Download Format
- The most common approach is for the server to return a public access URL (e.g., a cloud storage CDN link, or a path to a static file hosted on your server). Your Angular app can then use this URL to download the file (via a link with
downloadattribute) or display it (e.g.,<img [src]="fileUrl">for images). - For small files, you could also return the file content as a Base64-encoded string, but this is not recommended for large files as it increases payload size significantly.
内容的提问来源于stack exchange,提问作者Akshay Golash

