django实现快速文件上传

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了django实现快速文件上传相关的知识,希望对你有一定的参考价值。

摘自http://www.cnblogs.com/fnng/p/3740274.html

数据库

from django.db import models

# Create your models here.
class User(models.Model):
    username = models.CharField(max_length = 30)
    headImg = models.FileField(upload_to = ‘test/‘)  #注意是路径是跟在MEDIA_ROOT下

    def __unicode__(self):
        return self.username

模板

<?xml version="1.0" encoding="UTF-8"?> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title></title>
</head>
<body>
<h1>register</h1>
<form method="post" enctype="multipart/form-data" >
{{uf.as_p}}
<input type="submit" value="ok"/>
</form>
</body>
</html>

视图

#coding=utf-8
from django.shortcuts import render,render_to_response
from django import forms
from django.http import HttpResponse
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()
    return render_to_response(‘register.html‘,{‘uf‘:uf})

  

csrf设置:setting.py中注释

MIDDLEWARE_CLASSES = (
    ‘django.contrib.sessions.middleware.SessionMiddleware‘,
    ‘django.middleware.common.CommonMiddleware‘,
    #‘django.middleware.csrf.CsrfViewMiddleware‘,
    ‘django.contrib.auth.middleware.AuthenticationMiddleware‘,
    ‘django.contrib.messages.middleware.MessageMiddleware‘,
    ‘django.middleware.clickjacking.XFrameOptionsMiddleware‘,
)

  

技术分享技术分享

 

以上是关于django实现快速文件上传的主要内容,如果未能解决你的问题,请参考以下文章

django 快速实现文件上传

Django实现文件的上传

django中使用FastDFS分布式文件系统接口代码实现文件上传下载更新删除

[django]modelform实现的多文件上传

django实现文件上传(最简单的方法)

PHP 快速实现大文件上传