0

我需要从以下位置复制文件:

<form action="test_edit_info" method="POST" enctype="multipart/form-data">
    {%csrf_token%}
    <input type="file" name="avatar">
    <input type="submit" value="Register"/>
</form>

到我的静态目录(只需将模板中的文件复制到 STATIC 中)

鉴于:_

def test_edit_info(request):
if request.method == "POST" :
    new_ava = request.FILES['avatar']
    print "new ava: ",new_ava #return file-name
c = {}
c.update(csrf(request))
return render(request, "test_edit_personal_information.html")

只需将文件从模板复制到静态目录。没有任何形式和模型。帮助,请。谢谢。

4

2 回答 2

0

首先,staticdir 就像它的名字一样:STATIC。它仅包含静态文件,如自定义 js、静态图像、css ...

如果你想上传文件,你应该使用media目录。

观点:别忘了导入设置

from django.conf import settings

if request.method == 'POST':
    if 'avatar' in request.FILES:
        file = request.FILES['avatar']

        # Other data on the request.FILES dictionary:
        #   filesize = len(file['content'])
        #   filetype = file['content-type']

        filename = file['filename']

        fd = open('%s/%s' % (settings.MEDIA_ROOT, filename), 'wb')
        fd.write(file['content'])
        fd.close()

        #return ...
于 2013-06-28T23:47:04.737 回答
0

谢谢,但有错误:“InMemoryUploadedFile”对象没有属性“ getitem ”文件名=文件[“文件名”]

那么,这个呢?

from django.core.files.storage import default_storage
from django.core.files.base import ContentFile
def test_edit_info(request):
    if request.method == 'POST':
        if 'avatar' in request.FILES:
            file = request.FILES['avatar']
            default_storage.save("E:/reg_extend_2/static/img/avatars/%s"%(file), ContentFile(file.read()))
    c = {}
    return render(request, "test_edit_personal_information.html")
于 2013-07-01T10:43:52.280 回答