web123456

Use NodeJS to implement file upload, transcoding, and preview functions (zero front-end)

async function uploadFile(ctx: RouterContext) { const files: Files = ctx.request.files; if (!(files && files.image)) { ctx.body = HoResponseUtils.error<any>({ error_no: 100301 }); return; } if (files.image && files.image['length']) { ctx.body = HoResponseUtils.error<any>({ error_no: 100302 }); return; } ca_logger.info(upload_conf); try { // Save as a local temporary file const tmpPath = await _saveFile(files); // Decompression const originPath = upload_conf.outputPath + '/origin'; const imgPathListStr = await _decompression(tmpPath, originPath); // Transcoding const thumbPath = upload_conf.outputPath + '/thumb'; await _thumbImgList(imgPathListStr, thumbPath); } catch (error) { ctx.body = HoResponseUtils.error<any>({ error_no: 100302, error_message: error }); return; } ctx.body = HoResponseUtils.normal<any>({ data: 'Uploaded successfully' }); return; } // Rename it to image and save it as a local temporary file function _saveFile(files): Promise<string> { const file = files.image as File; const suffix = file.name.split('.').pop(); const tmpPath = `${upload_conf.tempPath}/images.${suffix}`; return new Promise((resolve, reject) => { try { caUtils.mkdir(tmpPath); const data = fs.readFileSync(file.path); fs.writeFileSync(tmpPath, data) resolve(tmpPath); } catch (err) { reject('File reading failed,Please upload the correct compressed folder! ') } }); } /** * @param tempPath * @param outputPath * Read the compressed file in the tempPath path. After decompression, put the decompressed file into outputPath * After decompression, temporary files can be deleted or not deleted. Each upload will be renamed to image. The second upload will overwrite the compressed files uploaded for the first time. */ function _decompression(tempPath: string, outputPath: string): Promise<string> { const outputArr = []; const myStream = extractFull(tempPath, outputPath, { $bin: pathTo7zip, $progress: true }); return new Promise((res, rej) => { myStream.on('data', function (data) { outputArr.push(upload_conf.host + '/upload/origin/' + data.file) }); myStream.on('end', function () { ca_logger.info('Complete!'); if (outputArr.length) { res(outputArr.join(',')); } else { rej('The folder is empty, please upload the correct compressed folder! '); } }); myStream.on('error', (err) => { ca_logger.error('Error:', err) rej('File decompression failed, please upload the correct compressed folder! '); }); }); }