问题
I'm looking for a way to implement client side file (image) upload from jquery to Django-Tastypie.
So far server side seems correct testing with CURL:
I found this post helpfull Django-tastypie: Any example on file upload in POST?
EDIT : This is what i did with curl ->
in 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 FooResource(MultipartResource, ModelResource):
img = fields.FileField(attribute="img", null=True, blank=True)
class Meta:
queryset = Foo.objects.all()
authorization= Authorization()
in models.py :
class Foo(models.Model):
img = models.ImageField(upload_to="images", null=True, blank=True)
body = models.CharField(max_length=255)
Then running the following command with curl :
curl -v -F "body=test" -F "img=@my_picture.png" http://localhost:8000/api/v1/foo/
Now i'm trying to do the same with jquery as client instead of curl.....with no luck. It's difficult to find a working example for Jquery+Tastypie for file upload...
If you have any simple example available thanks for sharing
回答1:
If you mean using $.ajax()
or $.post()
then it won't work because Ajax doesn't support file uploads. See e.g. this SO post.
There are some workarounds though - e.g. uploading via form in hidden iframe or flash-based solutions - they are discussed in the SO post mentioned above. None of them are perfect though, so you will have to choose the one which best serves your use case.
回答2:
In case anybody stumbles upon this in the future, I got image upload working (which was working using curl
already) in my case using this jquery File Upload Demo on github.
Use the Basic file upload:
- Include necessary js files (jquery, jquery-fileupload, iframe-transport, and jquery.ui.widget).
- Initialize the target
input[type=file]
control as shown below
Code:
$('#fileupload').fileupload({
url: url,
dataType: 'json',
done: function (e, data) {
$.each(data.result.files, function (index, file) {
$('<p/>').text(file.name).appendTo('#files');
});
},
progressall: function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
$('#progress .progress-bar').css(
'width',
progress + '%'
);
}
}).prop('disabled', !$.support.fileInput)
.parent().addClass($.support.fileInput ? undefined : 'disabled');
This should do the trick.
来源:https://stackoverflow.com/questions/15263964/django-tasypie-image-upload-example-with-jquery