Django实现文件的上传

需求:自己写一个文件上传功能

代码:

urls.py

from django.conf.urls import url
from django.contrib import admin
from app01 import views


urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^upload.html$', views.upload),
]

views.py

from django.shortcuts import render
from django.shortcuts import redirect
from django.shortcuts import HttpResponse
from app01 import models
import os

#实现文件上传功能
def upload(request):
    if request.method == 'GET':
        return render(request,'upload.html')
    elif request.method == 'POST':
        obj = request.FILES.get('fafafa')
        f = open(os.path.join('upload',obj.name),'wb')
        for line in obj.chunks():
            f.write(line)
        f.close()
        return HttpResponse('上传成功')

upload.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/upload.html" method="POST" enctype="multipart/form-data">
    {% csrf_token %}
    <input type="file" name="fafafa" />
    <input type="submit" value="上传" />
</form>
</body>
</html>

运行结果:


 文件上传:

  -普通上传

  -自定义页面上传按钮

  -基于Form做上传

  -Ajax上传文件(后补)

 

升级版

settings.py

STATIC_URL = '/static/'
STATICFILES_DIRS = (
    os.path.join(BASE_DIR,'static'),
) 

urls.py

from django.conf.urls import url
from django.contrib import admin
from app01 import views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^upload.html$', views.upload),
]

views.py

from django.shortcuts import render
from django.shortcuts import HttpResponse
from django.forms import fields
from django import forms


class UploadForm(forms.Form):
    user = fields.CharField()
    img = fields.FileField()

def upload(request):
    if request.method == 'GET':
        return render(request,'upload.html')
    else:
        # obj = UploadForm(request.POST,request.FILES)
        # if obj.is_valid():
        #     user = obj.cleaned_data['user']
        #     img = obj.cleaned_data['img']
        user = request.POST.get('user')
        img  = request.FILES.get('img')
        # img是对象(文件大小,文件名称,文件内容。。。)
        print(img.name)
        print(img.size)
        f = open(img.name,'wb')
        for line in img.chunks():
            f.write(line)
        f.close()
        return HttpResponse('...')

upload.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="/upload.html" method="POST" enctype="multipart/form-data">
        {% csrf_token %}
        <input type="text" name="user" />
        <div style="position: relative">
            <a>NB上传</a>
            <input type="file" name="img" style="opacity: 0;position:absolute;top:0;left: 0;" />
        </div>
        <input type="submit" value="提交" />
    </form>
</body>
</html>

运行效果:

 

posted @ 2016-07-30 23:16  许二哈哈哈  阅读(567)  评论(0编辑  收藏  举报