【发布时间】:2019-05-27 09:15:15
【问题描述】:
我在我的 cloudflare worker 中收到一个请求,并希望将数据上传到 Google 云存储。我的问题是我无法从收到的 multipart/form-data 数据中提取内容类型,以便将具有正确内容类型的内容上传到 GCS。
当我使用 await req.formData() 读取请求时,我可以从 formData 中 get('file') 并返回 GCS 所需的原始文件数据,但我似乎无法在任何地方看到我所需要的文件内容类型需要(我只能在查看原始请求正文时看到它)。
这是我的(简化的)代码:
event.respondWith((async () => {
const req = event.request
const formData = await req.formData()
const file = formData.get('file')
const filename = formData.get('filename')
const oauth = await getGoogleOAuth()
const gcsOptions = {
method: 'PUT',
headers: {
Authorization: oauth.token_type + ' ' + oauth.access_token,
'Content-Type': 'application/octet-stream' //this should by `'Content-Type': file.type`
},
body: file,
}
const gcsRes = await fetch(
`https://storage.googleapis.com/***-media/${filename}`,
gcsOptions,
)
if (gcsRes.status === 200) {
return new Response(JSON.stringify({filename}), gcsRes)
} else {
return new Response('Internal Server Error', {status: 500, statusText: 'Internal Server Error'})
}
})())
提醒 - 该代码是我们 cloudflare worker 代码的一部分。
在我看来,这应该是直截了当的,确定您从 multipart/form-data 数据中提取的文件类型。 我错过了什么吗?
【问题讨论】:
-
Content-typehttp 的标头将是multipart/form-data。当您提到文件类型时,您是在谈论 .jpg .png 等文件扩展名吗? -
是的,请求内容类型是
mulipart/form-data我想要的是在表单数据中发送的文件数据的类型。它可以是任何文件类型。问题是,在 cloudflare 中,我没有 Blob 对象,我相信它会在节点服务器场景中捕获文件类型。 -
你认为从文件名读取文件扩展名是你的选择吗?
标签: javascript node.js http multipartform-data cloudflare-workers