python+mysql上传图片和上传文件

一、上传与展示图片

参考博客http://www.cognize.me/2016/05/09/djangopic

开始之前要先安装python图像处理库:

pip install --use-wheel Pillow


1、数据库设置


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

例如:

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


这里的upload_to是指定图片存储的文件夹名称,上传文件之后会自动创建

 

1.4. 更新数据库

python manage.py makemigrations
python manage.py migrate

 

2、修改配置文件setting.py

只需要在最后的静态文件区加上下面两行代码:

MEDIA_ROOT = os.path.join(BASE_DIR, 'media').replace('\\', '/')     #设置静态文件路径为主目录下的media文件夹
MEDIA_URL = '/media/'                                                 #url映射

3、创建模板


3.1. 在APP目录下创建文件夹templates  

注意:这是django默认的形式,如果想把模板放在其他路径,得自己重新配置。


3.2. 在templates文件夹下创建文件夹,比如叫img_tem

 

3.3. 在img_tem下创建模板


uploadimg.html

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


showimg.html

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


这里img是Django的Model里的一个实例对象,使用img.img.url可以获取他的url,而且在settings.py中已经对其做了静态映射

4、创建视图函数 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)

5、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)  这句话是用来指定和映射静态文件的路径

121022_iHVB_3018050.png

完成之后就可以发布了。

 

二、上传与下载文件

 

1、数据库设置


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

 

2、修改配置文件setting.py

只需要在最后的静态文件区加上下面两行代码:

MEDIA_ROOT = os.path.join(BASE_DIR, 'media').replace('\\', '/')     #设置静态文件路径为主目录下的media文件夹
MEDIA_URL = '/media/'                                                 #url映射

3、创建模板


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中已经对其做了静态映射

4、创建视图函数 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)

5、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)


124820_gqZh_3018050.png

完成之后就可以发布了。

转载于:https://my.oschina.net/u/3018050/blog/1788523

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值