你如何上传与Django的tastypie POST请求文件? [重复](How do you

2019-07-17 18:25发布

可能重复:
Django的tastypie:在POST文件上传任何的例子吗?

我现在做的卷曲POST请求我的API,像这样

curl --dump-header - -H "Content-Type: application/json" -X POST --data '{"username":"theusername", "api_key":"anapikey", "video_title":"a title", "video_description":"the description"}' http://localhost:8000/api/v1/video/ 

但现在我需要能够将视频文件添加到上传。 我一直在四处寻找有关与Tastypie上传文件了几个小时,我还没有想出了一个坚实的响应。 我是否需要添加Base64编码? 如果是的话怎么样? 如何存取权限的文件,我有一个POST请求上传之后呢? 只是正常request.FILES行动? 我并不想将文件保存到数据库中,刚刚得到的文件路径。

#Models.py
class Video(models.Model):
    video_uploader = models.ForeignKey(User)
    video_path = models.CharField(max_length=128)
    video_views = models.IntegerField(default=0)
    upload_date = models.DateTimeField(auto_now_add=True)
    video_description = models.CharField(max_length=860)
    video_title = models.SlugField()

我是如何实现文件上传系统Tastypie所以任何帮助将是非常赞赏彻底糊涂了。 谢谢!

Answer 1:

这里是由路要上传的文件MultiPart通过django-tastypie

Models.py

class Video(models.Model):
    video_uploader = models.ForeignKey(User)
    video = models.FileField(_('Video'), upload_to='path_to_folder/') # save file to server
    video_views = models.IntegerField(default=0)
    upload_date = models.DateTimeField(auto_now_add=True)
    video_description = models.CharField(max_length=860)
    video_title = models.SlugField()

Api.py

class MultipartResource(object):
    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()
            data.update(request.FILES)
            return data
        return super(MultipartResource, self).deserialize(request, data, format)

class VideoResource(MultipartResource, ModelResource):
   """
   Inherit this Resource class to `MultipartResource` Class
   """
   # Assuming you know what to write here 
   ...

然后通过CURL

curl -H "Authorization: ApiKey username:api_key" -F "video=/path_to_video/video.mp3" -F "video_title=video title" http://localhost:8000/api/v1/video/ -v


文章来源: How do you upload a file with a POST request on django-tastypie? [duplicate]