Django文件上传与下载(FileFlid)

yipeiwu_com6年前Python基础

本文实例为大家分享了Django文件上传与下载的具体代码,供大家参考,具体内容如下

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" rel="external nofollow" >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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python面向对象编程中的类和对象学习教程

Python中一切都是对象。类提供了创建新类型对象的机制。这篇教程中,我们不谈类和面向对象的基本知识,而专注在更好地理解Python面向对象编程上。假设我们使用新风格的python类,它...

使用PyTorch将文件夹下的图片分为训练集和验证集实例

PyTorch提供了ImageFolder的类来加载文件结构如下的图片数据集: root/dog/xxx.png root/dog/xxy.png root/dog/xxz.png...

关于你不想知道的所有Python3 unicode特性

我的读者知道我是一个喜欢痛骂Python3 unicode的人。这次也不例外。我将会告诉你用unicode有多痛苦和为什么我不能闭嘴。我花了两周时间研究Python3,我需要发泄我的失望...

python Matplotlib底图中鼠标滑过显示隐藏内容的实例代码

python Matplotlib底图中鼠标滑过显示隐藏内容的实例代码

在使用Matplotlib画图过程中,有些内容必须鼠标点击或者划过才可以显示,这个问题可以依赖于annotate(s='str' ,xy=(x,y) ,xytext=(l1,l2) ,....

Python 实现文件读写、坐标寻址、查找替换功能

Python 实现文件读写、坐标寻址、查找替换功能

读文件 打开文件(文件需要存在) #打开文件 f = open("data.txt","r") #设置文件对象 print(f)#文件句柄 f.close() #关闭文件 #为了方...