我有发送文件到服务器的客户端:
public uploadFile(url: string, filePath: string): Promise<ICommandResponse<void>> {
const body = new FormData();
body.append('file', fs.createReadStream(filePath));
return this.instance.post(url, body, {
headers: {
'Content-Type': 'multipart/form-data',
},
})
.then((response) => {
this.verify(response.status);
return response.data;
})
.catch((err) => {
throw error(
`Failed to upload file from server: ${err?.message}`,
{ status: err?.response?.status ?? HttpStatus.InternalServerError },
);
});
}
在服务器中,我正在使用 Multer 将文件上传到 S3。我在上传文件之前验证了用户的访问令牌:
private getUploader(config: IHttpServerConfig) {
if (!config.s3Bucket) {
throw error('S3 bucket is not configured', {
status: HttpStatus.InternalServerError,
});
}
const s3Client = new S3Client({
region: config.s3Bucket.region,
credentials: {
accessKeyId: config.s3Bucket.accessKeyId,
secretAccessKey: config.s3Bucket.secretAccessKey,
},
});
return this.#uploader ??= multer({
storage: multerS3({
s3: s3Client,
bucket: config.s3Bucket.name,
contentType: multerS3.AUTO_CONTENT_TYPE,
key: (_req, file, cb) => {
cb(null, file.originalname);
},
}),
fileFilter: (req, file, cb) => {
try {
const accessToken = req.cookies[AuthCookieKey.AccessToken];
this.authorizeToken(accessToken);
return cb(null, true);
} catch (err) {
return cb(err, false);
}
},
});
}
虽然我在上传文件之前验证了用户的访问令牌,但看起来 Multer 在验证之前开始上传文件,突然我收到以下错误:“无法从服务器上传文件:写入 EPIPE”。
知道为什么吗?
谢谢。