Django

时间:2015-05-05 13:47:36

标签: python django

这是我上传基于类视图中定义的图像的代码,

def _handle_uploaded_file(self, request):

        folder = settings.MEDIA_ROOT
        uploaded_filename = request.FILES['img_fl'].name

        BASE_PATH ='/home/admin1/Desktop/virtualenv-12.1.1/mapfied'
        # create the folder if it doesn't exist.
        try:
            os.mkdir(os.path.join(BASE_PATH, folder))
        except Exception as e:
            pass

        # save the uploaded file inside that folder.
        full_filename = os.path.join(BASE_PATH, folder, uploaded_filename)

        fd = open(full_filename, 'wb')

        file_content = ContentFile( request.FILES['img_fl'].read() )

        try:
            for chunk in file_content.chunks():
                fout.write(chunk)
            fout.close()
                html = "<html><body>SAVED</body></html>"
                print(html)
        except Exception as e:
            print(e)

图像文件被保存到名称正确的位置,但它已损坏。我无法找到确切的原因,我在这里做错了吗?

2 个答案:

答案 0 :(得分:2)

这是我之前用于将上传文件写入磁盘的项目所具有的:

findViewById

答案 1 :(得分:1)

我认为既然您正在寻找二进制上传文件,则需要使用可写二进制模式打开文件,实际上是 wb +

您还可以使用'with'关键字整理一下;请参阅Django示例here

旁注:如果您将文件保存为FileField(或派生类),则可以提供“upload_to”函数,该函数返回您要存储文件的位置的完整路径和文件名。这将让框架为您处理文件io。