juliomalegria / django-chunked-upload

Upload large files to Django in multiple chunks, with the ability to resume if the upload is interrupted.
MIT No Attribution
214 stars 71 forks source link

Best Practice for POST to ChunkedUploadCompleteView using Fetch? #59

Open banagale opened 3 years ago

banagale commented 3 years ago

I struggled to POST to a subclass of ChunkedUploadCompleteView

While the jquery .ajax() post seems to form the request perfectly, I could not get the right combination of headers on my fetch post.

I believe this is because the view is expecting a form to be involved because in _post() the request is expected to have request.POST.get('upload_id') to retrieve upload_id

As a result, POSTing to ChunkedUploadCompleteView with fetch did not see the upload_id or md5 in the body of my fetch-based POSTs.

I ended up overriding _post to change how the view found the two variables like this:

class MyChunkedUploadCompleteView(ChunkedUploadCompleteView):
    # ...

    def _post(self, request, *args, **kwargs):
        request_body = json.loads(request.read().decode('utf-8'))
        upload_id = request_body['upload_id']
        md5 = request_body['md5']

        error_msg = None
        if self.do_md5_check:
        # ...

My fetch method on the javascript side looks like this:

const postData = (url, data) => {
  const csrfToken = getCSRFTokenCookie('csrftoken');
  return fetch(url, {
    method: 'POST',
    credentials: 'same-origin',
    headers: {
      'X-CSRFToken': csrfToken,
      "Accept": "application/json",
      "Content-Type": "application/json"
    },
    body: JSON.stringify(data)
  });
};

This works just fine for posting to ChunkedUploadView which does not require accessing request.POST.

Here's .ajax() post that does supply a request.POST

  $.ajax({
    type: "POST",
    url: url,
    data: data,
    dataType: "json",
    success: function (data) {
      console.log(data);
    }
  });

Is there a better way to handle getting data to this view using fetch apart from overriding this internal function?