简体   繁体   中英

Pass text to python via a CGI form field that expects a file

I have two servers. Server A hosts a python script upload.py for uploading a file; this script expects the file to be passed in a form field:

form = cgi.FieldStorage()

if "upload-file" not in form:
    print("Need an upload file")
else:
    fileItem = form["upload-file"]

    if not fileItem.file:
        print("Not a file")
    else:
        fileContent = fileItem.file.read()
        outFilePath = os.path.join("/some/path/", fileItem.filename)
        outFile = open(outFilePath, "wb")
        outFile.write(fileContent)
        # etc.

This script works, and the way it handles its input cannot be changed, because of an existing HTML/JavaScript UI that relies on this interface.

Now I want to call the above script from another python script residing on server B. So I need to do something similar to this:

import requests

# Call script on server A
response = requests.post(
    "http://10.20.30.40/cgi-bin/upload.py",
    files = { "upload-file": "some file content" })

This actually does create a file on server A, but it is named upload-file . So I want to control the value of fileItem.filename (in the script on server A) when calling it from server B. How can I achieve that? The CGI field name upload-file must not change. I tried to use the params argument of the post method, but didn't get it to work that way (I'm new to python, and just googling things as I go along).

Found the answer:

files = {"upload-file": ("desired-file-name.xml", "some file content")}

response = requests.post(
    "http://10.20.30.40/cgi-bin/upload-xml.py",
    files = files)

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