[英]How to upload image to folder and name to database using python
這是我的代碼,用於將圖像上傳到文件夾並將名稱上傳到數據庫,但它不起作用。 我收到錯誤“字節”object 沒有屬性“圖像”發生異常
#html code -->#
<html>
<head>
<TITLE> Product Image</TITLE>
</head>
<body>
<form enctype="multipart/form-data" action="productimg.py" method=post>
<table align=center cellspacing=20 cellpadding=10 >
<th align="center" colspan=3 > <u>Upload Image of the Goods</u></th>
<tr ><th colspan="4"> Enter your details below and wait minimum for half an hour.</th></tr>
<tr>
<td> Product Image : </td><td> <input type=file name="image" accept = "image/*" accept=".png/*" value="image"> </td>
</tr>
<tr>
<td> </td> <td> <input type=Submit > <input type=Reset> </td>
</tr>
</table>
</form>
</body>
</html>
我收到錯誤“字節”object 沒有屬性“圖像” pyhton 代碼中發生異常。
#python代碼-->#
#!C:\Users\Pc\AppData\Local\Programs\Python\Python38-32\python.exe
print('Content-type:text/html\n\r')
import cgi
import sys
from myconnect import *
message=0
try:
con,cur=myconnect()
form= cgi.FieldStorage()
# Get here.
fileitem=form.getvalue('image');
#fileitem = form['image']
# Test if the file was uploaded
if fileitem.image:
# strip leading path from file name to avoid
# directory traversal attacks
fn = os.path.basename(fileitem.image)
open('/uploads/' + fn, 'wb').write(fileitem.file.read())
message = 'The file "' + fn + '" was uploaded successfully'
query=f"select product_delivery_id from tbl_product_deliver order by product_delivery_id desc"
cur.execute(query)
pid=cur.fetchone()
update=f"UPDATE `tbl_product_deliver` SET `product_image`='{fn}' WHERE `product_delivery_id`='{pid}'"
cur.execute(update)
con.commit()
else:
message = 'No file was uploaded'
except Exception as e:
print(e)
print("Exception occured")
您不能使用 python 腳本,例如 php。通常,您必須配置事件處理程序以等待后請求。 要在 python 中執行此操作,您需要一個類似flask的框架或bottle來接收發布請求,而不是productimg.py ,您使用您在此框架中設置的路由作為html中的操作。
您的FieldStorage object在沒有 arguments 的情況下被調用,因此您創建了一個沒有數據的空 Fieldstorge object。
一個 FieldStorage object 收到一個 post 請求看起來像這樣:
fs= FieldStorage(fp=request.body, headers=request.headers, environ={'REQUEST_METHOD':'POST', 'CONTENT_TYPE':request.headers['Content-Type'], })
但是請確保在執行問題 2 之前解決了問題 1。
對於瓶子,請使用此 python 代碼:
from bottle import post, request, run
@post('/upload')
def getImage():
#printing the raw data
print(request.body)
#insert your code here
run(host='localhost', port=8080)
並更改 html: action="http://localhost:8080/upload
祝你好運
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.