简体   繁体   中英

python CGI variable json

I need to show uploaded file size in JSON format on Python. Here is my code:

def save_uploaded_file (form_field, upload_dir):

    form = cgi.FieldStorage()
    if not form.has_key(form_field): print 0; return
    fileitem = form[form_field]
    if not fileitem.file: print 0; return
    varfilepath = os.path.join(upload_dir, fileitem.filename)
    fout = file (varfilepath, 'wb')
    while 1:
        chunk = fileitem.file.read(100000)
        if not chunk: break
        fout.write (chunk)
    fout.close()
    varfilesize = os.path.getsize(varfilepath)
    data['filesize'] = varfilesize
    print simplejson.dumps(data)

save_uploaded_file ("file_1", UPLOAD_DIR)

But I got error:

<type 'exceptions.NameError'>: global name 'data' is not defined 
      args = ("global name 'data' is not defined",) 
      message = "global name 'data' is not defined"

您将不得不创建地图data

data = {'filesize': varfilesize}

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