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

作者: tmpbook
发布时间:2015-07-29 11:32:07

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

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title></title>
</head>
<a href="update/20140711/005zEPW4jw1eg3js7sil3g30500824al.gif">gao</a>
<body>
  <h1>register</h1>
  <form method="post" enctype="multipart/form-data" >
    {% csrf_token %}
    {{uf.as_ul}}
    <input type="submit" value="ok" />
  </form>
</body>
</html>


上传成功!

数据库中是这么个情况:


接下来是下载

我的文件目录是:

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

MEDIA_ROOT = HERE

版权声明:本文为博主原创文章,未经博主允许不得转载。

标签: Django Go
来源:http://blog.csdn.net/tmpbook/article/details/38331383

推荐: