我的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.body
if (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 = item
let localFileArr = localFile.split('/')
let key = `ai/assistants/${now}-${
localFileArr[localFileArr.length - 1]
}`
let historyKey = key
putExtra.checkCrc = false
formUploader.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',
})
}
}