Итак, я работал с загрузками GraphQL, и перед тем, как заявить о своей проблеме, вот обзор используемого мной стека технологий:
Серверная часть: Mongoose, Express, Apollo, GraphQL
Внешний интерфейс: VueJS, Apollo, GraphQL
Я использую Клиент загрузки Apollo для отправки Загрузить файлов на серверную часть от клиента.Поскольку я отправляю список файлов типа скалярная выгрузка с клиента, я получаю список обещаний, которые необходимо решить.При использовании Promise.all () я получаю следующую ошибку (которая, как ни странно, раньше не получалась, и я не знаю почему).Если я загружаю более одного файла, первый файл просто теряется где-то, а второй загружается ... Но это не всегда.Иногда этого не происходит.Может быть, я не решаюсь или не выполняю обещания должным образом.Обратите внимание, что мне также нужно сохранить имя файла в MongoDB через Mongoose
{ BadRequestError: Request disconnected during file upload stream parsing.
at IncomingMessage.request.once (F:\repos\pushbox\node_modules\graphql-upload\lib\processRequest.js:245:35)
at Object.onceWrapper (events.js:285:13)
at IncomingMessage.emit (events.js:197:13)
at resOnFinish (_http_server.js:583:7)
at ServerResponse.emit (events.js:202:15)
at onFinish (_http_outgoing.js:683:10)
at processTicksAndRejections (internal/process/next_tick.js:74:9)
message: 'Request disconnected during file upload stream parsing.',
expose: true,
statusCode: 499,
status: 499 }
У меня есть тег ввода HTML-файла, который принимает несколько файлов, и я использую мутацию:
async uploadFiles() {
// Check if input tag is empty
if (this.files.length === 0) {
this.uploadErrorAlert = true;
return;
}
// Mutation
this.isUploading = true;
await this.$apollo.mutate({
mutation: UPLOAD_FILES,
variables: {
files: this.files,
id: this.selectedCard.id,
},
})
.then(() => {
// clear files from the input tag
this.files = '';
this.$refs.selectedFiles.value = '';
this.isUploading = false;
})
.catch((err) => {
console.error(err);
});
},
И, наконец, распознаватель на сервере:
/**
* Uploads files sent on disk and saves
* the file names in the DB
*
* @param {Object} attachments - List of files for a card
*
* @return {Boolean} - true if upload is
* successful
*/
uploadFiles: async (_, attachments, { controllers }) => {
Promise.all(attachments.files.map(async (file) => {
const { createReadStream, filename } = await file;
const stream = createReadStream();
/**
* We need unique names for every file being uploaded,
* so we use the ID generated by MongoDB and concat it
* to the filename sent by the user.
*
* Therefore we instantiate an attachment object to get an ID
*/
const attachment = await controllers.attachment.add({ id: attachments.id, file: '' });
const newFileName = `${attachment.id}_${filename}`;
const path = `${process.env.UPLOAD_DIR}/${newFileName}`;
await controllers.attachment.update({
id: attachment.id,
file: newFileName,
});
console.log(`reached for ${path}`);
// Attempting to save file in server
return new Promise((resolve, reject) => stream
.pipe(createWriteStream(path))
.on('finish', () => resolve())
.on('error', (error) => {
console.log('dude?');
if (stream.truncated) {
// Delete the truncated file
unlinkSync(path);
}
reject(error);
}));
})).then(() => {
pubsub.publish(ATTACHMENTS_ADDED, { attachmentsChanged: controllers.attachment.getAll() });
}).catch((err) => {
console.log(err);
});
},
Любая помощь будет оценена!