本文主要是介绍如何根据openai官网的FileID下载文件,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
我的chatgpt网站,哈哈: https://chat.xutongbao.top/
file-type的版本需要注意:
"file-type": "^15.0.0",
const FileType = require('file-type')const assistantsDownloadFileOnAzure = async (req, res) => {let { apiKey = 'sk-xxx', fileIds = [] } = req.bodyif (apiKey === apiKeyOnServer) {if (Array.isArray(fileIds) && fileIds.length > 0) {let promiseListForDownload = fileIds.map((item) => {return new Promise(async (resolve, reject) => {const fileRes = await openai.files.content(item)const bufferView = new Uint8Array(await fileRes.arrayBuffer())let buffer = Buffer.from(bufferView)FileType.fromBuffer(buffer).then((fileTypeBlobRes) => {console.log('fileTypeBlobRes', fileTypeBlobRes)if (fileTypeBlobRes?.ext) {let localPath = `/temp/ai/assistants/${Date.now()}.${fileTypeBlobRes?.ext}`fs.writeFile(localPath,bufferView,(err) => {if (err) {throw err}console.log('The file has been saved!')resolve(localPath)})} else {reject()}})})})let localFileList = await Promise.all(promiseListForDownload)let promiseListForUpload = localFileList.map((item) => {return new Promise((resolve) => {// 文件上传let now = Date.now()let localFile = itemlet localFileArr = localFile.split('/')let key = `ai/assistants/${now}-${localFileArr[localFileArr.length - 1]}`let historyKey = keyputExtra.checkCrc = falseformUploader.putFile(uploadToken,key,localFile,putExtra,async function (respErr, respBody, respInfo) {if (respErr) {console.log('上传SD图片失败【1】', respErr)}if (respInfo.statusCode == 200 ||(respInfo.statusCode === 614 &&respBody.error === 'file exists')) {let key = ''if (respBody.data) {key = respBody.data.key}if (!key) {key = historyKey}resolve(key)} else {console.log(respInfo.statusCode)console.log('上传SD图片失败【2】', respBody)}})})})let cdnFileList = await Promise.all(promiseListForUpload)res.send({code: 200,data: {fileIds,localFileList,cdnFileList,},message: '成功',})} else {res.send({code: 400,message: '失败:参数fileIds',})}} else {res.send({code: 400,message: '失败:参数apiKey',})}
}
这篇关于如何根据openai官网的FileID下载文件的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!