我目前正在向我的API发出cURL POST请求
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实现文件上传系统感到非常困惑,所以任何帮助都将非常感激。谢谢!
答案 0 :(得分:13)
以下是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