Django-文件上传与下载(FileFlid)

Django1.4

首先是上传:

#settings.py

MEDIA_ROOT = HERE#定义一个完整路径给 MEDIA_ROOT 以便让 Django在此处保存上传文件

MEDIA_URL = 'media'#定义 MEDIA_URL 作为该目录的公共 URL,要确保该目录对 WEB 服务器用户帐号是可写的


#model.py

#coding=utf-8

from django.db import models
class User(models.Model):
    username = models.CharField(max_length = 30)
    headImg = models.FileField(upload_to = 'update/%Y%m%d')
    
    def __unicode__(self):
        return self.username



#view.py

#coding=utf-8

from django.shortcuts import render_to_response
from django import forms
from django.http import HttpResponse
from django.template import RequestContext
from disk.models import User

# Create your views here.
class UserForm(forms.Form):
    username = forms.CharField()
    headImg = forms.FileField()
    
def register(request):
    if request.method == "POST":
        uf = UserForm(request.POST, request.FILES)
        if uf.is_valid():
            #获取表单信息
            username = uf.cleaned_data['username']
            headImg = uf.cleaned_data['headImg']
            #写入数据库
            user = User()
            user.username = username
            user.headImg = headImg
            user.save()
            return HttpResponse('upload ok!')
    else:
        uf = UserForm()
    ur= User.objects.order_by('id')
    return render_to_response('register.html',{'uf':uf}, context_instance=RequestContext(request))



前台使用{{uf.as_ul}}来展示form,如下:


#register.html



    
    

gao

  

register

{% csrf_token %} {{uf.as_ul}}


上传成功!

数据库中是这么个情况:

Django-文件上传与下载(FileFlid)_第1张图片


接下来是下载

我的文件目录是:

Django-文件上传与下载(FileFlid)_第2张图片

要想下载你首先要知道,你上传的东西到了哪个目录,涉及到两个地方:

MEDIA_ROOT = HERE

你可能感兴趣的:(django)