問題描述
我有一個 HTML 表單,我正在使用 Python 根據輸入生成一個日志文件.如果用戶愿意,我還希望能夠允許用戶上傳圖片.一旦它在那里,我可以弄清楚如何用 Python 操作它,但我不確定如何上傳圖像.這肯定是以前做過的,但我很難找到任何例子.你們誰能指出我正確的方向嗎?
I have an HTML form and I am using Python to generate a log file based on the input. I'd like to also be able to allow the user to upload an image if they choose. I can figure out how to manipulate it with Python once it's there, but I'm not sure how to get the image uploaded. This has most certainly been done before, but I'm having a hard time finding any examples. Can any of you point me in the right direction?
基本上,我使用 cgi.FieldStorage
和 csv.writer
來制作日志.我想從用戶的計算機上獲取圖像,然后將其保存到我服務器上的目錄中.然后我將重命名它并將標題附加到 CSV 文件中.
Basically, I'm using cgi.FieldStorage
and csv.writer
to make the log. I want to get an image from the user's computer and then save it to a directory on my server. I will then rename it and append the title to the CSV file.
我知道這有很多選擇.我只是不知道它們是什么.如果有人可以指導我獲取一些資源,我將非常感激.
I know there are a lot of options for this. I just don't know what they are. If anyone could direct me toward some resources I would be very appreciative.
推薦答案
既然你說你的特定應用程序是與 python cgi 模塊一起使用的,那么快速谷歌就會找到很多例子.這是第一個:
Since you said that your specific application is for use with the python cgi module, a quick google turns up plenty of examples. Here is the first one:
最小 http 上傳 cgi(Python 配方) (剪輯)
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()
此代碼將獲取文件輸入字段,該字段將是一個類似文件的對象.然后它將逐塊讀取到輸出文件中.
This code will grab the file input field, which will be a file-like object. Then it will read it, chunk by chunk, into an output file.
2015 年 4 月 12 日更新:根據評論,我添加了對這個舊的 activestate 片段的更新:
Update 04/12/15: Per comments, I have added in the updates to this old activestate snippet:
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)
這篇關于使用 Python 上傳文件的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!