python 圖片上傳寫入磁盤功能

本文是採起django框架,前端上傳圖片後端接收後寫入磁盤,數據庫記錄圖片在磁盤上的路徑(相對),如下是前端上傳到後端入庫的基本流程html

一. 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"  將文件以二進制的形式上傳,這樣能夠實現多種類型的文件上傳python

2、後端接收代碼mysql

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/')

3、file_info功能代碼web

#!/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

4、最後settings.py配置媒體目錄sql

MEDIA_URL = '/media/'
MEDIA_ROOT=os.path.join(BASE_DIR,'media/')

5、附上數據庫的配置(本身好忘怎麼配)數據庫

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'dbdatabase',
        'USER': 'dbusername',
        'PASSWORD': 'dbpassword',
        'HOST': '192.168.xx.xx',
        'PORT': '3306',
        'charset':'utf8'
    }
}
相關文章
相關標籤/搜索