[英]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. 我需要获取用户上传的文件并将其存储在本地PC上。 can this be done in python ? 可以在python中完成吗? please let me know. 请告诉我。
mod_python includes the FieldStorage
class which allows you access to uploaded form data. mod_python包含FieldStorage
类 , 该类使您可以访问上载的表单数据。 In order to use it, you'd put something like the following in your Python script: 为了使用它,您需要在Python脚本中添加以下内容:
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). 由于fdesc
是文本输入,因此description
将是一个字符串(更确切地说是一个StringField
,您可以将其视为字符串)。
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. 由于fname
是文件输入,因此file_field
将不是字符串(或StringField
),而是允许您访问文件数据的Field
对象。 The attribute file_field.file
is a file-like object which you can use to read the file's contents, for example like so: 属性file_field.file
是一个类似文件的对象,您可以使用它来读取文件的内容,例如:
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. file_field.filename
是客户端提供的文件名。 Other useful attributes are listed in the documentation I linked to. 我链接到的文档中列出了其他有用的属性。
也许最小的http cgi上传食谱 ,它的评论对您有帮助。
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. 感谢您的帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.