我有一个HTML表单,我使用Python根据输入生成一个日志文件。我还想让用户在他们选择时上传图片。我可以弄清楚如何使用Python操作它,但我不知道如何上传图像。这肯定在以前完成,但我很难找到任何例子。你们中的任何人都能指出我正确的方向吗?
基本上,我使用cgi.FieldStorage
和csv.writer
来制作日志。我想从用户的计算机上获取图像,然后将其保存到我服务器上的目录中。然后我将重命名它并将标题附加到CSV文件。
我知道有很多选择。我只是不知道它们是什么。如果有人能引导我走向某些资源,我将非常感激。
答案 0 :(得分:8)
由于您说您的特定应用程序是与python cgi模块一起使用的,因此快速google会提供大量示例。这是第一个:
Minimal http upload cgi (Python recipe)( snip )
def save_uploaded_file (form_field, upload_dir):
"""This saves a file uploaded by an HTML form.
The form_field is the name of the file input field from the form.
For example, the following form_field would be "file_1":
<input name="file_1" type="file">
The upload_dir is the directory where the file will be written.
If no file was uploaded or if the field does not exist then
this does nothing.
"""
form = cgi.FieldStorage()
if not form.has_key(form_field): return
fileitem = form[form_field]
if not fileitem.file: return
fout = file (os.path.join(upload_dir, fileitem.filename), 'wb')
while 1:
chunk = fileitem.file.read(100000)
if not chunk: break
fout.write (chunk)
fout.close()
此代码将获取文件输入字段,该字段将是一个类文件对象。然后它将按块查看它,并将其读入输出文件。
更新04/12/15 :根据评论,我在这个旧的activestate代码段的更新中添加了:
import shutil
def save_uploaded_file (form_field, upload_dir):
form = cgi.FieldStorage()
if not form.has_key(form_field): return
fileitem = form[form_field]
if not fileitem.file: return
outpath = os.path.join(upload_dir, fileitem.filename)
with open(outpath, 'wb') as fout:
shutil.copyfileobj(fileitem.file, fout, 100000)
答案 1 :(得分:3)
网络框架工作金字塔有一个很好的例子。 http://docs.pylonsproject.org/projects/pyramid_cookbook/en/latest/forms/file_uploads.html
这是我用于工作项目的示例代码。
extension = os.path.splitext(request.POST[form_id_name].filename)[1]
short_id = str(random.randint(1, 999999999))
new_file_name = short_id + extension
input_file = request.POST[form_id_name].file
file_path = os.path.join(os.environ['PROJECT_PATH'] + '/static/memberphotos/', new_file_name)
output_file = open(file_path, 'wb')
input_file.seek(0)
while 1:
data = input_file.read(2<<16)
if not data:
break
output_file.write(data)
output_file.close()