מעלה את הקוד המתוקן שלי שמציע כמה שיפורים, ב"ה כעת זה עובד.
import fs from 'fs/promises';
const baseUrl = 'https://www.call2all.co.il';
async function* getChunks(filePath, chunkSize) {
const file = await fs.open(filePath, 'r');
const buffer = Buffer.alloc(chunkSize);
try {
while (true) {
const result = await file.read(buffer, 0, chunkSize);
if (result.bytesRead === chunkSize)
yield result.buffer;
else {
yield result.buffer.slice(0, result.bytesRead);
break;
}
}
} finally {
await file.close();
}
}
function createFormData(bytes, contentName, partialData = null) {
const data = {
token: tokenYemot,
path: remotePath,
convertAudio: 1,
autoNumbering: 0
};
if (partialData) {
data.uploader = 'yemot-admin';
data.qquuid = partialData.uuid;
data.qqfilename = contentName;
data.qqtotalfilesize = partialData.fileSize;
data.qqtotalparts = partialData.partCount;
//in final post request we don't need to send the file
if (partialData.part < partialData.partCount) {
data.qqpartbyteoffset = chunkSize * partialData.part;
data.qqpartindex = partialData.part;
data.qqchunksize = bytes.length;
}
}
const formData = new FormData();
for (const [key, value] of Object.entries(data))
formData.append(key, value);
if(bytes)
formData.append( partialData ? 'qqfile' : 'file', new Blob([bytes]), {filename: contentName, contentType: 'application/octet-stream'});
return formData;
}
let tokenYemot = '';
const chunkSize = 20000000;
const remotePath = 'ivr2:/';
async function uploadFile(filePath) {
const fileSize = (await fs.stat(filePath)).size;
const callApi = (url, payload) => fetch(url, {method: 'POST', body: payload});
const chunks = getChunks(filePath, chunkSize);
const contentName = filePath.split('/').pop();
if (fileSize <= chunkSize) {
const formData = createFormData((await chunks.next()).value, contentName);
await chunks.return();
return await callApi(baseUrl + '/ym/api/UploadFile', formData).then(x => x.json());
} else {
const uuid = crypto.randomUUID();
const partCount = Math.ceil(fileSize / chunkSize);
let part = 0;
for await (const chunk of chunks) {
const formData = createFormData(chunk, contentName, {uuid, fileSize, partCount, part: part++});
const status = await callApi(baseUrl + '/ym/api/UploadFile', formData).then(x => x.json());
if (!status.success) {
console.log(status);
throw new Error(status.message);
}
}
return await callApi(baseUrl + '/ym/api/UploadFile?done', createFormData(null, contentName,
{uuid, fileSize, partCount, part})).then(x => x.text());
}
}