Skip to content
This repository has been archived by the owner on Mar 18, 2019. It is now read-only.

support multipart/form-data (e.g. file uploads) #44

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

chrisv2
Copy link

@chrisv2 chrisv2 commented Nov 16, 2017

This patch enables file uploads by allowing multipart/form-data encoding in transport.

Usage example

(this took me a while to figure out, feel free to add this to the docs)

Server (Django)

from rest_framework import serializers, viewsets, parsers

# serializer with file field
class AttachmentSerializer(serializers.Serializer):
    file = serializers.FileField(write_only=True)

# viewset with upload method
class MyViewset(viewsets.ModelViewSet):
  # ...
  @detail_route(methods=['post'],
                serializer_class=AttachmentSerializer, 
                parser_classes=(parsers.MultiPartParser,))
  def add_attachment(self, request, *args, **kwargs):
      serializer = serializers.AttachmentSerializer(data=request.data)
      if serializer.is_valid():
          # serializer.validated_data['file'] is an instance of django.core.files.File
          print("uploaded file: %s" %  serializer.validated_data['file']

Client (JS)

const client = new coreapi.Client()
const schema = window.schema

// file must be either an instance of Blob (for content generated in JS) or 
// an instance of File (retrieved from an <input type="file"> or a dropEvent.FileList)

client.action(schema,
              ['mymodel', 'add_attachment'],
              {id: id, file: file})
      .then((result) => console.log(result))

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant