python+mysql上傳圖片和上傳文件

1、上傳與展現圖片

參考博客http://www.cognize.me/2016/05/09/djangopichtml

開始以前要先安裝python圖像處理庫:python

pip install --use-wheel Pillow


一、數據庫設置


1.1. 先建立一個app,好比叫img_db。

命令行:python manage.py startapp img_db數據庫

1.2. 將其加入到settings.py文件中的INSTALLED_APPS中

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'img_db',
    'corsheaders',
]

 

1.3. 在models.py中建立表,圖片存儲使用的是 models.ImageField

例如:django

class IMG(models.Model):
    img = models.ImageField(upload_to='img')
    name = models.CharField(max_length=100)


這裏的upload_to是指定圖片存儲的文件夾名稱,上傳文件以後會自動建立session

 

1.4. 更新數據庫

python manage.py makemigrations
python manage.py migrateapp

 

二、修改配置文件setting.py

只須要在最後的靜態文件區加上下面兩行代碼:cors

MEDIA_ROOT = os.path.join(BASE_DIR, 'media').replace('\\', '/')     #設置靜態文件路徑爲主目錄下的media文件夾
MEDIA_URL = '/media/'                                                 #url映射

三、建立模板


3.1. 在APP目錄下建立文件夾templates  

注意:這是django默認的形式,若是想把模板放在其餘路徑,得本身從新配置。函數


3.2. 在templates文件夾下建立文件夾,好比叫img_tem

 

3.3. 在img_tem下建立模板


uploadimg.htmlpost

<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="img">
<button type="submit">上傳</button>
</form>


showimg.htmlurl

{% for img in imgs %}
<img src="{{ img.img.url }}" />
{% endfor %}


這裏img是Django的Model裏的一個實例對象,使用img.img.url能夠獲取他的url,並且在settings.py中已經對其作了靜態映射

四、建立視圖函數 view.py

@csrf_exempt
def uploadImg(request):
    if request.method == 'POST':
        new_img = IMG(
            img=request.FILES.get('img'),
            name = request.FILES.get('img').name
        )
        new_img.save()
    return render(request, 'img_tem/uploadimg.html')


首先用get方式訪問uploadImg(),而後會跳轉到uploadimg.html頁面,上傳文件時會使用post再次訪問uploadImg(),這時就會將圖片存儲在數據庫與media/img_tem中。

@csrf_exempt
def showImg(request):
    imgs = IMG.objects.all()
    content = {
        'imgs':imgs,
    }
    for i in imgs:
        print i.img.url
    return render(request, 'img_tem/showimg.html', content

views.py下代碼整理:

from django.shortcuts import render

from img_db.models import IMG
# Create your views here.
# @csrf_exempt
def uploadImg(request):
    if request.method == 'POST':
        new_img = IMG(
            img=request.FILES.get('img'),
            name = request.FILES.get('img').name
        )
        new_img.save()
    return render(request, 'img_tem/uploadimg.html')

# @csrf_exempt
def showImg(request):
    imgs = IMG.objects.all()
    content = {
        'imgs':imgs,
    }
    for i in imgs:
        print (i.img.url)
    return render(request, 'img_tem/showimg.html', content)

五、url.py配置

from django.conf.urls import url
from django.contrib import admin
import view
from django.conf.urls.static import static
from django.conf import settings

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^upload', view.uploadImg),
    url(r'^show', view.showImg),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)  這句話是用來指定和映射靜態文件的路徑

完成以後就能夠發佈了。

 

2、上傳與下載文件

 

一、數據庫設置


1.1. 先建立一個app,好比叫file_db。

命令行:python manage.py startapp file_db

1.2. 將其加入到settings.py文件中的INSTALLED_APPS中

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'file_db',
    'corsheaders',
]

 

1.3. 在models.py中建立表,文件存儲使用的是 models.FileField

例如:

from __future__ import unicode_literals
from django.db import models

# Create your models here.
class User(models.Model):
    username = models.CharField(max_length = 30)
    filename = models.FileField(upload_to = './file/')

    def __unicode__(self):
        return self.username


這裏的upload_to是指定文件存儲的文件夾名稱,上傳文件以後會自動建立

 

1.4. 更新數據庫

python manage.py makemigrations
python manage.py migrate

 

二、修改配置文件setting.py

只須要在最後的靜態文件區加上下面兩行代碼:

MEDIA_ROOT = os.path.join(BASE_DIR, 'media').replace('\\', '/')     #設置靜態文件路徑爲主目錄下的media文件夾
MEDIA_URL = '/media/'                                                 #url映射

三、建立模板


3.1. 在APP目錄下建立文件夾templates  

注意:這是django默認的形式,若是想把模板放在其餘路徑,得本身從新配置。


3.2. 在templates文件夾下建立文件夾,好比叫file_tem

 

3.3. 在file_tem下建立模板


uploadfile.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>upload file</h1>
    <form method="post" enctype="multipart/form-data" >
        {{ form.as_p }}
        <input type="submit" value="Submit" />
    </form>
</body>
</html>


showfile.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
{% for file in files %}
    <a href="{{ file.filename.url }}" >{{ file.username }}</a>
{% endfor %}
</body>
</html>


這裏file是Django的Model裏的一個實例對象,使用file.filename.url能夠獲取他的url,並且在settings.py中已經對其作了靜態映射

四、建立視圖函數 view.py

def uploadfile(request):
    if request.method == 'POST':
        form = UserForm(request.POST, request.FILES)
        if form.is_valid():
            # 獲取表單數據
            username = form.cleaned_data['username']
            filename = form.cleaned_data['filename']
            # 獲取數據庫數據
            user = User()
            user.username = username
            user.filename = filename
            user.save()
            return HttpResponse('file upload ok !')
    else:
        form = UserForm()
    return render_to_response('file_tem/uploadfile.html', {'form': form})

 

def showfile(request):
    files = User.objects.all()
    content = {
        'files': files,
    }
    for i in files:
        print(i.filename.file)
    return render(request,'file_tem/showfile.html',content)

views.py下代碼整理:

# -*- coding:utf-8 -*-
from django.shortcuts import render
from django.shortcuts import render_to_response
from django import forms
from django.http import HttpResponse
from file_db.models import User

# Create your views here.
class UserForm(forms.Form):
    username = forms.CharField()
    filename = forms.FileField()

def uploadfile(request):
    if request.method == 'POST':
        form = UserForm(request.POST, request.FILES)
        if form.is_valid():
            # 獲取表單數據
            username = form.cleaned_data['username']
            filename = form.cleaned_data['filename']
            # 獲取數據庫數據
            user = User()
            user.username = username
            user.filename = filename
            user.save()
            return HttpResponse('file upload ok !')
    else:
        form = UserForm()
    return render_to_response('file_tem/uploadfile.html', {'form': form})

def showfile(request):
    files = User.objects.all()
    content = {
        'files': files,
    }
    for i in files:
        print(i.filename.url)
    return render(request,'file_tem/showfile.html',content)

五、url.py配置

# from django.contrib import admin

from django.conf.urls.static import static
from django.conf import settings
from django.conf.urls import url

from file_db import views as file_db



urlpatterns = [
    # url(r'^admin/', admin.site.urls),
    url(r'^uploadfile', file_db.uploadfile),

] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


完成以後就能夠發佈了。

相關文章
相關標籤/搜索