在Tastypie中保存base64编码的文件 [英] Save base64 encoded file in Tastypie

查看:251
本文介绍了在Tastypie中保存base64编码的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



这是模型。

 class MessageAttachments(models.Model):
filename = models.CharField(max_length = 100)
file_size = models.IntegerField(max_length = 100)
attachment = models $($)

def __unicode __(self):
return self.filename

内部api.py我写了我自己的函数来保存消息附件。

  def send(self,request,** kwargs):
self.method_check(request,allowed = ['post'])
data = self.deserialize(request,request.body,format = request.META .get('CONTENT_TYPE','application / json')
file_data = data.get('attach','')
try:
b = file_data.encode('utf-8 ')
message_attach = MessageAttachments()
message_attach.filename ='file'
message_attach.file_size ='file'
message_attach.attachment = ContentFile(b64decode(b),'test')
message_attach.save()
return self.create_response(request,{
'success':True,
'msg':msg.id
})
除了:
return self.create_response(request,{
'success' False
})

正如你所看到的,我尝试过ContentFile。但它不工作。我也需要从中获取文件大小。字符串存储在变量file_data中。我尝试从base64 b64decode。即使解码工作文件没有存储。



使用python 3.4和django 1.6。

解决方案

我不知道其他版本的Tastypie是否有差异,但对于v0.10.0(及更低版本)这个问题的答案建议的方法对我有用:





这是一个覆盖反序列化 TastyPie的 ModelResource

  class MultipartResource(object):

用于上传的多部分资源

反序列化文件/图像上传的资源定义
*请参阅:
https: /github.com/toastdriven/django-tastypie/issues/42


def deserialize(self,request,data,format = None):
如果不是格式:
format = request.META.get('CONTENT_TYPE','application / json')

如果format =='application / x-www-form-urlencoded':
return request.POST

如果format.startswith('multipart'):
data = request.POST.copy()
upload = request.FILES
data .update(上传)
返回数据

返回超级(MultipartResource,self).deserialize(请求,数据,格式)

在您的 api.py 中,您将声明您的资源,并正常访问反序列化数据:

  class MyResource(MultipartResource,ModelResource):

def hydrate(self,bundle):
upload = bundle.data.get 'attach')
#....

注意:这假设您的前端正在将数据作为常规POST数据发送到您的API - 上传不需要编码。但是它需要作为multipart / form-data发送:

 < form action =#method = postenctype =multipart / form-data> 
...


Am doing a project in angular js and django.

This is the model.

class MessageAttachments(models.Model):
    filename = models.CharField(max_length=100)
    file_size = models.IntegerField(max_length=100)
    attachment = models.FileField(upload_to='files/')

    def __unicode__(self):
        return self.filename

Inside api.py i wrote my own function to save message attachments.

def send(self, request, **kwargs):
        self.method_check(request, allowed=['post'])
        data = self.deserialize(request, request.body, format=request.META.get('CONTENT_TYPE', 'application/json'))
        file_data = data.get('attach', '')
        try:
            b = file_data.encode('utf-8')
            message_attach = MessageAttachments()
            message_attach.filename =  'file'
            message_attach.file_size = 'file'
            message_attach.attachment = ContentFile(b64decode(b), 'test')
            message_attach.save()
            return self.create_response(request, {
                    'success': True,
                    'msg': msg.id
                })         
        except:
            return self.create_response(request, {
                    'success': False
                })

As you can see i tried ContentFile . But its not working. I need to get the file size too from that. The string is stored inside variable file_data. i tried b64decode from base64. Even though the decoding works file is not stored.

Am using python 3.4 and django 1.6.

解决方案

I'm not sure if there are differences in other versions of Tastypie, but for v0.10.0 (and below) the method suggested by the answer to this question has worked for me:

This is an example of a Resource class that overrides the deserialize methof of TastyPie's ModelResource:

class MultipartResource(object):
    """
    multi-part resource for uploads

    Resource definition for deserializing file/image uploads
    * see:
    https://github.com/toastdriven/django-tastypie/issues/42

    """
    def deserialize(self, request, data, format=None):
        if not format:
            format = request.META.get('CONTENT_TYPE', 'application/json')

        if format == 'application/x-www-form-urlencoded':
            return request.POST

        if format.startswith('multipart'):
            data = request.POST.copy()
            upload = request.FILES
            data.update(upload)
            return data

        return super(MultipartResource, self).deserialize(request, data, format)

In your api.py you would declare your resource like this and access the deserialized data normally:

class MyResource(MultipartResource, ModelResource):

    def hydrate(self, bundle):
        upload = bundle.data.get('attach')
        # ....

Note: This assumes your frontend is sending data to your API as regular POST data -- the upload does not need to be encoded. But it needs to be sent as "multipart/form-data":

<form action="#" method="post" enctype="multipart/form-data">
...

这篇关于在Tastypie中保存base64编码的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆