Jac*_*gan 8 python upload cgi image
我有一个HTML表单,我使用Python根据输入生成一个日志文件.我还想让用户在他们选择时上传图片.我可以弄清楚如何使用Python操作它,但我不知道如何上传图像.这肯定在以前完成,但我很难找到任何例子.你们有人能指出我正确的方向吗?
基本上,我正在使用cgi.FieldStorage
并csv.writer
制作日志.我想从用户的计算机上获取一个图像,然后将其保存到我服务器上的目录中.然后我将重命名它并将标题附加到CSV文件.
我知道有很多选择.我只是不知道它们是什么.如果有人能指导我走向某些资源,我将非常感激.
既然你说你的特定应用程序是用于python cgi模块,那么快速谷歌会提供很多例子.这是第一个:
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()
Run Code Online (Sandbox Code Playgroud)
此代码将获取文件输入字段,该字段将是一个类文件对象.然后它会将其读取,按块分块,输入到输出文件中.
2015年12月4日更新:根据评论,我在这个旧的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)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
36705 次 |
最近记录: |