python 图片上传写入磁盘功能
本文是采取django框架,前端上传图片后端接收后写入磁盘,数据库记录图片在磁盘上的路径(相对),以下是前端上传到后端入库的基本流程
一. html代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="" method="post" enctype="multipart/form-data"> <p><input type="file" name="image"></p> <button type="submit" value="提交">提交</button> </form> </body> </html>
# 必须要加上 enctype="multipart/form-data" 将文件以二进制的形式上传,这样可以实现多种类型的文件上传
二、后端接收代码
from myweb.FileinfoPlug import file_info def news_add(request): if request.method == "GET": return render(request, 'image-add.html') else: input_image = request.FILES.get('image') image_name = file_info(input_image, 'article') print(image_name) models.Image.objects.create(title_img=image_name) return redirect('/images/')
三、file_info功能代码
#!/bin/env python # -*- coding: utf-8 -*- import os import time, random from django.conf import settings def file_Path(upload_to): file_path = os.path.join(settings.BASE_DIR, 'media', upload_to) if not os.path.exists(file_path): os.makedirs(file_path) return file_path def file_info(input_image,dirname=None): """ :param input_image: 前端传过来的二进制数据 :param dirname: 指定图片上传的目录,比如这里传入的是article,那么格式是 /media/article/images/2018/06/30/20180630133015_94.jpg :return: 最终如果想展示图片只需在orm取出数据库后加入 http://image.com/+/media/article/images/2018/06/30/20180630133015_94.jpg 拼接一下即可 """ fn = time.strftime('%Y%m%d%H%M%S') fn = fn + '_%d' % random.randint(0, 100) upload_to = time.strftime('images/%Y/%m/%d/') if dirname != None: upload_to = time.strftime(dirname+'/images/%Y/%m/%d/') file_suffix = input_image.name.split('.')[1] image_name = '{0}{1}.{2}'.format(upload_to, fn, file_suffix) filename = '{0}{1}{2}.{3}'.format(file_Path(upload_to), os.sep, fn, file_suffix) with open(filename, 'wb') as f: f.write(input_image.read()) return image_name
四、最后settings.py配置媒体目录
MEDIA_URL = '/media/' MEDIA_ROOT=os.path.join(BASE_DIR,'media/')
五、附上数据库的配置(自己好忘怎么配)
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'dbdatabase', 'USER': 'dbusername', 'PASSWORD': 'dbpassword', 'HOST': '192.168.xx.xx', 'PORT': '3306', 'charset':'utf8' } }