Possible Duplicate:
Django-tastypie: Any example on file upload in POST?
I currently do cURL POST requests to my API like so
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/
but now I need to be able to add a video file to the upload. I have been looking around for a few hours about uploading files with Tastypie and I have not come up with one solid response. Do I need to add the Base64 encode? If so how? How do I acces the file after I have uploaded it with a POST request? Just normal request.FILES actions? I am not looking to save the file to the database, just get the path to the file.
#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()
I am thoroughly confused on how to implement a file upload system for Tastypie so any help would be very appreciated. Thanks!
Here is way to upload file by MultiPart
through 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
...
And then through 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
来源:https://stackoverflow.com/questions/14119031/how-do-you-upload-a-file-with-a-post-request-on-django-tastypie