我正在尝试使用 Axios 将文件上传到端点,但我不断收到 400 错误“上传的文件为空”。 该文件根本不是空的 - 它大约有 90MB。 当我使用 Postman 上传到同一端点时,一切都完美地工作。事实上,它曾经通过代码完美地工作,但由于某种原因它开始失败。
这是代码:
async function uploadMediaToSermonAudio(URL, filePath) {
console.log('File Path: ', filePath)
const file = fs.createReadStream(filePath)
const response = await axios.post(URL, file);
if (response.status === 201) {
console.log('Media uploaded!');
data = response.data;
console.log('Data: ', data)
return true;
} else {
console.error('Media not uploaded:', response.statusText);
return false;
}
}
经过进一步调查,这似乎与从 Google Drive 下载文件的功能有关。当我手动下载时,上传成功。 奇怪的是,通过 Node 下载的文件似乎没有任何问题 - 它可以顺利播放。
这是首先获取文件的函数:
async function getDriveFile(auth, fileName, folderId) {
const drive = google.drive({ version: 'v3', auth });
// Recursive search to find the file in the folder or its subfolders
async function findFileInFolder(folderId) {
// Search for the file in the current folder
const res = await drive.files.list({
q: `name='${fileName}' and '${folderId}' in parents and trashed=false`,
fields: 'files(id, name, mimeType)',
});
if (res.data.files.length > 0) {
return res.data.files[0]; // Return the first match
}
// If the file is not found, search in subfolders recursively
const subfolders = await drive.files.list({
q: `'${folderId}' in parents and mimeType='application/vnd.google-apps.folder' and trashed=false`,
fields: 'files(id, name)',
});
for (const folder of subfolders.data.files) {
const foundFile = await findFileInFolder(folder.id);
if (foundFile) {
return foundFile;
}
}
return null; // If no file is found in this folder or its subfolders
}
// Start the search in the provided shared folder
const file = await findFileInFolder(folderId);
if (!file) {
throw new Error(`File not found: ${fileName}`);
}
// Download the file as a temporary file in the container
const filePath = path.join('/tmp/', file.name.toLowerCase());
const dest = fs.createWriteStream(filePath);
await drive.files.get(
{ fileId: file.id, alt: 'media' },
{ responseType: 'stream' },
function (err, res) {
if (err) {
throw err;
}
res.data.pipe(dest);
}
);
return filePath;
}
修好了!
我修改了 getDriveFile 函数中的管道调用以包含完成回调:
const promise = new Promise((resolve, reject) => {drive.files.get(
{ fileId: file.id, alt: 'media' },
{ responseType: 'stream' },
function (err, res) {
if (err) {
reject(err);
}
res.data.pipe(dest).on('finish', () => {resolve(filePath)});
}
);});
promise.then((res) => {
})
.catch((e) => {
console.log(e);
});
return promise;