Найти - Пользователи
Полная версия: загрузка с веб изображения в базу Mysql
Начало » Python для новичков » загрузка с веб изображения в базу Mysql
1
tortik
Доброго времени суток. Пытаюсь загрузить картинку через форму на сайте. Пока получается только загрузка пустых строк. в mysql использую таблицу blob.
Очень новичек) Буду рад помощи


 @app.route('/pythonlogin/111', methods=['GET', 'POST'])
def 111():
    if 'loggedin' in session:
        msg = ''
        if request.method == 'POST' and 'image' in request.form:
            image = request.form['image']
            cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
            cursor.execute('SELECT * FROM images WHERE image = %s', (image,))
            img = cursor.fetchone()
            if img:
                msg = 'Такая картинка есть'
            elif not image:
                msg = 'Пожалуйста, заполните форму!'
            else:
                cursor.execute('INSERT INTO images VALUES ( %s)', (image,))
                mysql.connection.commit()
                msg = 'загрузка успешна'
        elif request.method == 'POST':
            msg = 'нет нужного файла'
    return render_template('111.html', msg=msg)


 		<div class="image">
   			</div>
			<form action="{{ url_for('111') }}" enctype="multipart/form-data"  method="post" autocomplete="off">
                <input type="file" name="image" multiple accept="image/*,image/jpeg/jpg/png">
				<input type="submit" value="Загрузка">
				<div class="msg">{{ msg }}</div>
			</form>
		</div>
py.user.next
tortik
Пока получается только загрузка пустых строк.
Просто выведи в страницу все эти части, с которыми работаешь. Для этого используй repr().

Типа таких кусков
tortik
  
image = request.form['image']
  
image = request.form['image']
msg = msg + 'img: <{}>'.format(repr(image))

Вот так можно всё просмотреть - от пришедшей картинки, до открытой базы данных. Так ты и поймёшь, что не работает.
tortik
Немного поменял код. Теперь я сохраняю название файла
  <FileStorage: 'image.jpg' ('image/jpeg')>

 @app.route('/pythonlogin/111', methods=['GET', 'POST'])
def 111():
    if 'loggedin' in session:
        msg = ''
        if request.method == 'POST' and 'image1' in request.files:
            database = pymysql.connect(host="localhost", user="root", passwd="1111", db="1111")
            cursor = database.cursor()
            image = request.files.get('image1')
            sql = "INSERT INTO images VALUES  (%s);"
            args = (image)
            cursor.execute(sql, args)
            database.commit()
            cursor.close()
            database.close()
        return render_template('111.html', msg=msg)


     </head>
 	<body>
			<form action="{{ url_for('111') }}" method="post" enctype="multipart/form-data" >
                   <input type="file" name="image1" accept="image/*,image/jpeg/jpg/png" >
				   <input type="submit" value="load" >
			</form>
	</body>
</html>

где мог ошибиться?
tortik

py.user.next
Вот так можно всё просмотреть - от пришедшей картинки, до открытой базы данных. Так ты и поймёшь, что не работает.
в ответ он мне выдает то самое название картинки <FileStorage: ‘image.jpg’ ('image/jpeg')>
py.user.next
tortik
  
            args = (image)
            cursor.execute(sql, args)
Надо запятую добавить. Круглые скобки просто выражение образуют, а не кортеж.
  
args = (image,)

tortik
в ответ он мне выдает то самое название картинки
<FileStorage: ‘image.jpg’ ('image/jpeg')>
Загляни в объект. Используй функцию dir().

  
image = request.form['image']
msg += ' img: <{}>'.format(repr(dir(image)))
msg += ' req: <{}>'.format(repr(request))
msg += ' frm: <{}>'.format(repr(request.form))

Так постепенно поймёшь, что там есть.
tortik


py.user.next
Надо запятую добавить. Круглые скобки просто выражение образуют, а не кортеж.
Спасибо, тут уже поправлено.

img: <['__bool__', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattr__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parse_content_type', 'close', 'content_length', 'content_type', 'filename', 'headers', 'mimetype', 'mimetype_params', 'name', 'save', 'stream']>


req: <<Request 'http://127.0.0.1:5000/pythonlogin/111' [POST]>>

frm: <ImmutableMultiDict([('image1', <FileStorage: 'image.png' ('image/png')>)])>


Пока не могу понять что мне это дало. Еще только учусь)




py.user.next
Вот этот попробуй теперь
  
image = request.form['image']
msg += ' img: <{}>'.format(repr(dir(image)))
msg += ' strm: <{}>'.format(repr(dir(image.stream)))
tortik


img: <['__bool__', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattr__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parse_content_type', 'close', 'content_length', 'content_type', 'filename', 'headers', 'mimetype', 'mimetype_params', 'name', 'save', 'stream']>

strm: <['_TemporaryFileArgs', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__enter__', '__eq__', '__exit__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_check', '_file', '_max_size', '_rolled', 'close', 'closed', 'encoding', 'errors', 'fileno', 'flush', 'isatty', 'mode', 'name', 'newlines', 'read', 'readline', 'readlines', 'rollover', 'seek', 'softspace', 'tell', 'truncate', 'write', 'writelines']>


Я пока читаю про (request)
Экспериментирую с request.files. но пока также безуспешно




py.user.next
Дальше вот это. Там содержимое картинки в представимом виде.
  
image = request.form['image']
msg += ' dat: <{}>'.format(repr(image.stream.read()))
Чтобы чистые данные получить, надо убрать repr().
tortik
Спасибо огромное!!!! cursor.execute('INSERT INTO images VALUES (%s)', (image.stream.read(),)) вот так получилось!!!
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Powered by DjangoBB