[英]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.