私はHTMLフォームを持っており、Pythonを使用して、入力に基づいてログファイルを生成しています。ユーザーが選択した場合に画像をアップロードできるようにもしたいと思います。I Pythonがあれば、それを操作する方法を理解できますが、画像をアップロードする方法がわかりません。これは確かに以前に行われたことがありますが、私は苦労しています例を見つける時間です。誰かが私を正しい方向に向けることができますか?
基本的に、私はcgi.FieldStorage
とcsv.writer
を使用してログを作成しています。ユーザーのコンピューターから画像を取得して、サーバー上のディレクトリに保存したいと思います。次に、名前を変更して、CSVファイルにタイトルを追加します。
これにはたくさんのオプションがあることを私は知っています。私は彼らが何であるかを知らないだけです。誰かが私をいくつかのリソースに向けることができれば、私は非常に感謝しています。
あなたの特定のアプリケーションはpython cgiモジュールで使用するためのものであると言ったので、簡単なグーグルはたくさんの例を見つけます。これが最初のものです:
最小httpアップロードcgi(Pythonレシピ) (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)
WebフレームワークのPyramidには良い例があります。 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()