下面是一个使用
graphql-upload
和
apollo-server-express
包的单文件上传示例。
包版本:
"apollo-server-express": "^2.15.1",
"graphql-upload": "^12.0.0",
"graphql": "^14.6.0",
Nodejs版本:v14.16.0
。
GraphQL服务器:
import { ApolloServer, gql } from 'apollo-server-express';
import express from 'express';
import path from 'path';
import { createWriteStream, unlink } from 'fs';
import { graphqlUploadExpress } from 'graphql-upload';
const app = express();
const PORT = 3000;
const UPLOAD_DIR = path.resolve(__dirname, './uploads');
const typeDefs = gql`
scalar Upload
type Query {
dummy: String
}
type Mutation {
upload(upload: Upload!): Boolean
}
`;
const resolvers = {
Query: {},
Mutation: {
async upload(_, { upload }) {
const { file } = upload;
const { filename, mimetype, createReadStream } = await file;
const stream = createReadStream();
const id = Date.now();
const uploadPath = `${UPLOAD_DIR}/${id}-${filename}`;
console.log(filename, mimetype, createReadStream, stream);
await new Promise((resolve, reject) => {
const writeStream = createWriteStream(uploadPath);
writeStream.on('finish', resolve);
writeStream.on('error', (error) => {
unlink(uploadPath, () => {
reject(error);
});
});
stream.on('error', (error) => writeStream.destroy(error));
stream.pipe(writeStream);
});
return true;
},
},
};
app.use(
graphqlUploadExpress({
maxFileSize: 30000000,
maxFiles: 20,
}),
);
const server = new ApolloServer({
typeDefs,
resolvers,
uploads: false,
});
server.applyMiddleware({ app });
app.listen(PORT, () => console.log(`GraphQL server is listening on http://localhost:${PORT}/graphql`));
使用Altair GraphQL向客户端发送GraphQL请求。
![enter image description here](https://istack.dev59.com/OkeGU.webp)
服务器端的日志,成功获取
createReadStream
。
GraphQL server is listening on http://localhost:3000/graphql
matej-sefcik-GCRbVZydPT4-unsplash.jpg image/jpeg [Function: createReadStream] <ref *1> ReadStream {
_readableState: ReadableState {
objectMode: false,
highWaterMark: 16384,
buffer: BufferList { head: null, tail: null, length: 0 },
length: 0,
pipes: [],
flowing: null,
ended: false,
endEmitted: false,
reading: false,
sync: true,
needReadable: false,
emittedReadable: false,
readableListening: false,
resumeScheduled: false,
errorEmitted: false,
emitClose: true,
autoDestroy: true,
destroyed: false,
errored: null,
closed: false,
closeEmitted: false,
defaultEncoding: 'utf8',
awaitDrainWriters: null,
multiAwaitDrain: false,
readingMore: false,
decoder: null,
encoding: null,
[Symbol(kPaused)]: null
},
_events: [Object: null prototype] { close: [Function: remove] },
_eventsCount: 1,
_maxListeners: undefined,
_pos: 0,
_writeStream: WriteStream {
_writableState: WritableState {
objectMode: false,
highWaterMark: 16384,
finalCalled: false,
needDrain: true,
ending: false,
ended: false,
finished: false,
destroyed: false,
decodeStrings: true,
defaultEncoding: 'utf8',
length: 63781,
writing: true,
corked: 0,
sync: false,
bufferProcessing: false,
onwrite: [Function: bound onwrite],
writecb: [Function: nop],
writelen: 63781,
afterWriteTickInfo: null,
buffered: [],
bufferedIndex: 0,
allBuffers: true,
allNoop: true,
pendingcb: 1,
prefinished: false,
errorEmitted: false,
emitClose: true,
autoDestroy: false,
errored: null,
closed: false
},
_events: [Object: null prototype] {
error: [Array],
unpipe: [Function: onunpipe],
close: [Function],
finish: [Function],
ready: [Function],
drain: [Function: pipeOnDrainFunctionResult]
},
_eventsCount: 6,
_maxListeners: undefined,
_fd: null,
_path: null,
_pos: 0,
_readStreams: Set(1) { [Circular *1] },
_released: false,
_cleanupSync: [Function (anonymous)],
[Symbol(kCapture)]: false
},
[Symbol(kCapture)]: false
}
Upload success:
![enter image description here](https://istack.dev59.com/P9scf.webp)
源代码:https://github.com/mrdulin/apollo-graphql-tutorial/tree/master/src/file-upload
upload
变量/参数内部有额外的file
级别? - xadmupload
参数内的file
字段确实存在。我已经添加了我的源代码链接,请查看。 - Lin Du