1、upload.HTMl
<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>图片上传功能</h1>
<form method="post" enctype="multipart/form-data" >
{{uf.as_p}}
<input type="submit" value="ok"/>
</form> </body>
</html>
2、创建forms.py文件,(C:\djangoweb\helloworld\blog\forms.py)
#coding:utf-8
from django import forms class UserForm(forms.Form):
username = forms.CharField()
headImg = forms.FileField() class UploadFileForm(forms.Form):
title = forms.CharField(max_length=50)
file = forms.FileField() #处理这个form的视图收到了在request.FILES中的文件数据。
#从上述form来的数据以通过request.FILES['file']来存取
3、models文件
#coding:utf-8
from django.db import models class Teacher(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=)
class Meta:
db_table = 'teacher' class Student(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=)
age = models.IntegerField()
intime = models.DateField()
sex = models.IntegerField()
class Meta:
db_table = 'student' class User(models.Model):
username = models.CharField(max_length = )
headImg = models.FileField(upload_to = './photos/')
#图片上传之后存放在./photos/目录下,站点根目录下的photos目录中
#./代表站点根目录,../代表当前目录的上一级目录
class Meta:
db_table = 'User' def __unicode__(self):
return self.username #username 用户存放用户名,headImg 用户存放上传文件的路 4、配置urls文件
5、配置views文件
# Create your views here.
#coding:utf-8
from django.http import HttpResponse
import datetime
#导入templates文件所需导入库
from django.template import loader,Context
#引入Student等模块 from blog.models import *
from blog.forms import UserForm
from django.shortcuts import render,render_to_response def upload(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('upload.html',{'uf':uf}) 6、配置setting文件
##upload path,实现后台管理图片上传
#MEDIA_ROOT是用户上传的文件存储的位置,是文件系统上的路径,
#FileField, ImageField里面的upload_to的相对路径就是相对于MEDIA_ROOT的。
MEDIA_ROOT = 'C:/djangoweb/helloworld/upload' # URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://example.com/media/", "http://media.example.com/"
MEDIA_URL = '/upload/' TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
'/helloworld/blog/templates'
)