Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send file through Django Rest

I need to download image object from vary object storage buckets, and send that to a user through Django Rest Framework.

I have something like that:

if request.method == 'GET':

    # Get object using swiftclient
    conn = swiftclient.client.Connection(**credentials)
    container, file = 'container_name', 'object_name'
    _, data = conn.get_object(container, file)

    # Send object to the browser
    return Response(data, content_type="image/png")

data variable contains bytes type.

While testing I'm receiving error: 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte

What can be solution for this problem?

like image 795
sorryMike Avatar asked Mar 23 '18 10:03

sorryMike


People also ask

How do I import a CSV file into Django REST framework?

With all that done, you can go ahead and start your django server, navigate to the url you added which may look like this “http://127.0.0.1:8000/upload/”. Django Rest will display a page for you to upload your file, go ahead and upload a csv file using the sample data above and check your database to confirm it works.

What is JSONParser Django?

JSONParser. Parses JSON request content. request. data will be populated with a dictionary of data.


1 Answers

If you're looking to pass the image straight through Django Rest Framework to the user, it may be more appropriate to use an HttpResponse.

from django.http import HttpResponse

return HttpResponse(data, content_type="image/png")

Django Rest Framework's own Response will try and render the binary data which may cause the encoding issue you're seeing.

like image 112
Will Keeling Avatar answered Sep 19 '22 20:09

Will Keeling