0

there is my code: client:

def upload(url,file):
    file_name=file.split('\\')[-1]

    with open(file,'rb') as f:
        r=requests.post(url,data=f)

server side:

    $datastr = fopen('php://input',"rb");
    $filename='upload/111.bin';
    if ($fp = fopen($filename,"wb")){
    while(!feof($datastr)){
        fwrite($fp,fread($datastr,4096)) ;
        }
    }

it can work, but I don't know how to post the file stream with file name. if I use r=requests.post(url,data={ 'name':file_name, 'file':open(file,'rb') }), $_POST is null

1
  • if only post file stream, it can works with open(file,'rb') as f: r=requests.post(url,data=f) but I don't know how to post the stream with file name. Commented Apr 24, 2022 at 9:24

1 Answer 1

1

According to the documentation you can POST a multipart file with requests, but to POST it as a stream you should use requests-toolbelt.

If no streaming is actually required, you could modify your code to be:

def upload(url,file):
    file_name=file.split('\\')[-1]

with open(file,'rb') as f:
    r=requests.post(url,files={"file": (file_name, f)})

Using files in this way let’s you include file name and other header info (see docs for more information)

Sign up to request clarification or add additional context in comments.

3 Comments

I need to POST a stream, but I also need to know the name of stream file. So I'm confused with that.
Okay. See the requests toolbar link I included. You should build a multipart encoder and possibly wrap it in a monitor too. If that’s what you’re looking for I’ll edit my answer to include that
I have tried MultipartEncoder, if only post file stream it can work. but if I want to post file name and stream together, $_POST is null. Here is my code. def upload_multipart(url,file_path): file_name=file_path.split('\\')[-1] encoder=MultipartEncoder( fields={ 'filename':file_name, 'file':(file_name,open(file_path,'rb'),'application/octet-stream')}) data=MultipartEncoderMonitor(encoder,upload_callback) response=requests.post(url,data=data,headers={'Content-Type':data.content_type})

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.