Flask FileStorage object to File Object

2020-07-11 08:56发布

问题:

I have made an api through flask which submit a file and after receiving it on the back end , I want to further upload this to an unknown server using python requests module

The server accepts the file if I do this like -

requests.post(urlToUnknownServer,files={'file':open('pathToFile')})

Now my requirement is to get the file param uploaded through flask.
In flask I get the file as FileStorage object. I don't want to save this on my server, instead directly wants it to upload further.
So basically I want to convert that FileStorage object to return type of open() function which is file(please correct me here if I am wrong)

I had tried it using -

obj=file(request.files['fileName'].read().encode('string-escape'))
requests.post(urlToUnknownServer,files={'file':obj})

This doesn't work. Can it be possible to do that without saving file on my server.

回答1:

Maybe you can use read() without encoding it. such as this:

obj=request.files['fileName'].read()
requests.post(urlToUnknownServer,files={'file':obj})


回答2:

For anyone stuck with same problem, just convert to BufferedReader

like this:

    from io import BufferedReader
    image = request.files.get('name')
    image.name = image.filename
    image = BufferedReader(image)

and then you can post it

    requests.post(urlToUnknownServer,files={'file' : image})


回答3:

Try without file() constructor:

obj = request.files['fileName'].read().encode('string-escape')
requests.post(urlToUnknownServer,files={'file':obj})


标签: python flask io