接着之前的聊天服务器
做上用户头像上传。
考虑到性能问题,头像资料修改这些采用web服务器来做
以下代码只是测试。
models.py
from django.db import models
class ChatUser(models.Model):
uid = models.IntegerField(primary_key=True, db_index=True)
username = models.CharField(max_length=64)
password = models.CharField(max_length=64)
sex = models.IntegerField(default=0)
description = models.CharField(max_length = 256, blank=True, null=True)
headphoto = models.ImageField(upload_to='photos/users/' , blank=True, null=True)
class Meta:
db_table = 'user'
forms.py
from django.forms import ModelForm
from models import ChatUser
class UserForm(ModelForm):
class Meta:
model = ChatUser
fields = ( 'username' , 'password' , 'sex' , 'description', 'headphoto')
views.py
@csrf_exempt
def index(request):
c = {}
if request.method == 'POST':
form = UserForm(request.POST , request.FILES)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user = ChatUser.objects.filter( username = username, password = password )
if user:
print 'userhead ' , user[0].headphoto
path = settings.WEB_BASE_PATH + '/' + str(user[0].headphoto)
print path
import os
try:
os.remove( path )
except:
pass
import Image
uploaded = request.FILES['headphoto']
from django.core.files.base import ContentFile
file_content = ContentFile(uploaded.read())
user[0].headphoto.save( str(user[0].headphoto), file_content )
else:
form.save()
return HttpResponseRedirect('thanks.html')
else:
print 'error ' , form.errors
else:
form = UserForm(initial={'username':'watsy', 'password':'123123'})
c['form'] = form
return render_to_response('index.html', c)
iso客户端采用BeeFramework0.3版本,采用其他方式上传也可以
上传代码:
UIImage *image = [UIImage imageNamed:@"default_user_head"];
self.HTTP_POST( @"http://127.0.0.1:8000" )
.PARAM(@"username" , @"watsy")
.PARAM(@"password" , @"123123")
.PARAM(@"sex" , @"0")
.FILE_ALIAS(@"watsy.jpg" , UIImageJPEGRepresentation(image, 1) , @"headphoto" );