# coding=utf-8
import StringIO
from PIL import Image
from django.http import HttpResponse
from django.shortcuts import render_to_response
UPLOAD_URL = 'photo/upload/'
def upload(request):
buf = request.FILES.get('photo', None)
data = buf.read()
f = StringIO.StringIO(data)
image = Image.open(f)
image = image.convert('RGB')
name = '%s%s' % (UPLOAD_URL, buf.name)
image.save(file(name, 'wb'), 'PNG')
return HttpResponse('成功')
网上有写资料用buf['content']代替buf.read(),buf['filename']代替buf.name这样会出现异常
"<type 'exceptions.TypeError'>
'InMemoryUploadedFile' object is unsubscriptable
html代码:
<form method="POST" action="/photo/upload/" enctype="multipart/form-data">
选择图片: <input type="file" name="photo" /><br>
<input type="submit" value="上传">
</form>
enctype="multipart/form-data" 用于上传大文件,包含非ASCII码,以二进制形式上传