简体   繁体   中英

Apache + Python : Serving binairy files

I have an Apache server with python cgi (Python3). A client start a get request to get a virtual file, and I need to give him back the good one regarding his user-agent. I was able to do it with text files but when I try to serve back binairies files like images (.jpg) or .zip, the downloaded file seems corrupted.

When I parse it I can see b'\\x00\\x....' so I think the byte conversion went wrong somewhere.

I have tried with sys.stdout.write but it expects a str not bytes. I have tried also to "play" with the headers by changing the content type for example but it is not working.

reqFile = open(filePath,'rb')
content = reqFile.read()
print("Content-Type:image/jpg")
print("Accept-Rangers:byte")
print("Content-Length:"+str(len(content))
print()
print (content)

Thanks in advance !!

Ok, I have found that print() insert '\\n' character and other stuff. So, for binairies file, I recommend to use sys.stdout.

    file = open(filePath, "rb")
    content = file.read()
    length = len(content)
    file.close()

    print("Content-type:application/x-download")
    print("Content-length:%d" % length)
    print()

    sys.stdout.flush()
    sys.stdout.buffer.write(content)

Don't forget to do sys.stdout.flush() in order to have a clean output.

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