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

Multi tool use
Multi tool use












1















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?



Update: if you know the whey to achieve this in Node.js that will be useful as well.










share|improve this question

























  • Content-type header of the http would be multipart/form-data. Are you talking about file extensions like .jpg .png etc when you mention file type?

    – miradham
    Dec 31 '18 at 8:14











  • Yes, the request content-type is mulipart/form-data what I want is the type of the file data which is sent in the form-data. It can be any file type. The problem is that in cloudflare I don't have the Blob object that I believe would of captured the file type in a node server cenario.

    – Noam Silver
    Dec 31 '18 at 22:08











  • Do you think reading file extension from file name could be option for you?

    – miradham
    Jan 1 at 22:33
















1















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?



Update: if you know the whey to achieve this in Node.js that will be useful as well.










share|improve this question

























  • Content-type header of the http would be multipart/form-data. Are you talking about file extensions like .jpg .png etc when you mention file type?

    – miradham
    Dec 31 '18 at 8:14











  • Yes, the request content-type is mulipart/form-data what I want is the type of the file data which is sent in the form-data. It can be any file type. The problem is that in cloudflare I don't have the Blob object that I believe would of captured the file type in a node server cenario.

    – Noam Silver
    Dec 31 '18 at 22:08











  • Do you think reading file extension from file name could be option for you?

    – miradham
    Jan 1 at 22:33














1












1








1








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?



Update: if you know the whey to achieve this in Node.js that will be useful as well.










share|improve this question
















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?



Update: if you know the whey to achieve this in Node.js that will be useful as well.







javascript node.js http multipartform-data cloudflare-workers






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Dec 30 '18 at 16:15







Noam Silver

















asked Dec 30 '18 at 11:37









Noam SilverNoam Silver

63




63













  • Content-type header of the http would be multipart/form-data. Are you talking about file extensions like .jpg .png etc when you mention file type?

    – miradham
    Dec 31 '18 at 8:14











  • Yes, the request content-type is mulipart/form-data what I want is the type of the file data which is sent in the form-data. It can be any file type. The problem is that in cloudflare I don't have the Blob object that I believe would of captured the file type in a node server cenario.

    – Noam Silver
    Dec 31 '18 at 22:08











  • Do you think reading file extension from file name could be option for you?

    – miradham
    Jan 1 at 22:33



















  • Content-type header of the http would be multipart/form-data. Are you talking about file extensions like .jpg .png etc when you mention file type?

    – miradham
    Dec 31 '18 at 8:14











  • Yes, the request content-type is mulipart/form-data what I want is the type of the file data which is sent in the form-data. It can be any file type. The problem is that in cloudflare I don't have the Blob object that I believe would of captured the file type in a node server cenario.

    – Noam Silver
    Dec 31 '18 at 22:08











  • Do you think reading file extension from file name could be option for you?

    – miradham
    Jan 1 at 22:33

















Content-type header of the http would be multipart/form-data. Are you talking about file extensions like .jpg .png etc when you mention file type?

– miradham
Dec 31 '18 at 8:14





Content-type header of the http would be multipart/form-data. Are you talking about file extensions like .jpg .png etc when you mention file type?

– miradham
Dec 31 '18 at 8:14













Yes, the request content-type is mulipart/form-data what I want is the type of the file data which is sent in the form-data. It can be any file type. The problem is that in cloudflare I don't have the Blob object that I believe would of captured the file type in a node server cenario.

– Noam Silver
Dec 31 '18 at 22:08





Yes, the request content-type is mulipart/form-data what I want is the type of the file data which is sent in the form-data. It can be any file type. The problem is that in cloudflare I don't have the Blob object that I believe would of captured the file type in a node server cenario.

– Noam Silver
Dec 31 '18 at 22:08













Do you think reading file extension from file name could be option for you?

– miradham
Jan 1 at 22:33





Do you think reading file extension from file name could be option for you?

– miradham
Jan 1 at 22:33












1 Answer
1






active

oldest

votes


















0














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.






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53977276%2fhow-to-extract-the-content-type-of-a-file-sent-via-multipart-form-data%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    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.






    share|improve this answer




























      0














      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.






      share|improve this answer


























        0












        0








        0







        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.






        share|improve this answer













        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.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Jan 8 at 20:25









        Kenton VardaKenton Varda

        19.7k34653




        19.7k34653






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53977276%2fhow-to-extract-the-content-type-of-a-file-sent-via-multipart-form-data%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            hq,iKI 2JXtQca2RY6d0Cm
            SZI5g9ujBZ9xM,DSg,xpn9,buut,tI3laRe,jumvx21Vp

            Popular posts from this blog

            Monofisismo

            Angular Downloading a file using contenturl with Basic Authentication

            Olmecas