简体   繁体   中英

How to extract the Content-Type of a file sent via multipart/form-data

I receive a Request in my cloudflare worker and want to upload the data to Google cloud storage. My problem is that I can't extract the content type from the multipart/form-data data I receive in order to upload it with the correct content type to GCS.

When I read the request with await req.formData() I can get('file') from the formData and it returns the raw file data that I need for the GCS, but I can't seem to see anywhere the file content-type that I need (I can see it only when looking at the raw Request body).

Here is my (striped down) code :

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'})
  }
})())

Reminder - the code is part of our cloudflare worker code.

It seems to me this should be straight forward, determining the type of file you extract from the multipart/form-data data. Am I missing something?

Unfortunately, as of this writing, the Cloudflare Workers implementation of FormData is incomplete and does not permit extracting the Content-Type. In fact, it appears our implementation currently interprets all entries as text and return strings, which means binary content will be corrupted. This is a bug which will require care to fix since we don't want to break already-deployed scripts that might rely on the buggy behavior.

Thanks Kenton for your response.

What I ended up doing:

As the Cloudflare Workers don't support the multipart/form-data of Blob or any type other than String, I ended up using the raw bytes in the ArrayBuffer data type. After converting it to an Uint8Array I parsed it byte by byte to determine the file type and the start and end indexes of the file data. Once I found the start and end of the transferred file I was able create an array of the file data, add it to the request and send it to the GCS as I showed above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM