开发者

Need to get the uploaded file to my local PC

I have created a test form which will ask users to enter a name and upload the image file:

<html lang="en">
<head>
    <title>Testing image upload</title>
</head>
<body>
    <form action="/services/upload" method="POST" enctype="multipart/form-data">
    File Description: <input name='fdesc' type='text'><br>
    File name: <input type="file" name="fname"><br>
    <div><input type="submit"></div>
    </form>
</body>
</html>

i need to get the file uploaded by the user and store it on my local PC. can this be done in python ? pl开发者_C百科ease let me know.


mod_python includes the FieldStorage class which allows you access to uploaded form data. In order to use it, you'd put something like the following in your Python script:

req.form = FieldStorage(req)
description = req.form['fdesc']

Since fdesc is a text input, description will be a string (more precisely, a StringField, which you can treat as a string).

file_field = req.form['fname']

Since fname is a file input, file_field will not be a string (or StringField), but rather a Field object which allows you access to the file data. The attribute file_field.file is a file-like object which you can use to read the file's contents, for example like so:

for line in file_field.file:
    # process the line

You could use this to copy the file's data somewhere of your choosing, for example.

file_field.filename is the name of the file as provided by the client. Other useful attributes are listed in the documentation I linked to.


Maybie the minimal http cgi upload recipe and it's comments are helpful for you.


Hey David i got it working, i did it this way:

filename = request.FILES['fname']
destination = open('%s/%s'%(/tmp/,fileName), 'wb+')
for chunk in filename.chunks():
            destination.write(chunk)
destination.close()

file = open('%s/%s'%(/tmp/,fileName),"rb").read()

Thanks for the help guys.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜