0

Can you spot what I'm doing incorrectly?

Here is the Form (created in a template tag):

@register.simple_tag(takes_context=True)
def add_picture_upload(context,textarea_id):
  a = """<form style="display:none; visibility:hidden;" id="add_image_form" action="/fotos/upload/" method="post" enctype="multipart/form-data" >""" 
  b = """</form>"""
  form = PictureForm()
  return a+str(form)+b

Here the javascript that gets called on submit:

function html_add_image(event) {
  event.stopPropagation(); // Stop stuff happening
  event.preventDefault(); // Totally stop stuff happening
  var data_dict = new FormData($(this)[0]);
  var req = api_create("pictures", data_dict);
  req.done(function(data) {
    alert(data);
  })
}

Here the ajax request:

function api_create(content_name, data_dict) {
  var req = $.ajax({
      url: '/api/'+content_name+'/',
      contentType:"application/json",
      dataType: "json",
      data: data_dict,
      processData: false,
      type: 'POST'
  }).fail(function(jqXHR, status, err){
    // fail
  })
  return req;
}

It gives me:

detail: "JSON parse error - 'utf8' codec can't decode byte 0xff in position 148: invalid start byte"

Or if i JSON.stringify the data instead I get:

image_field: ["No file was submitted."]

Do you have any advice or a website that has a working example? I know many people are struggling with this, but all the other questions here don't really lead anywhere.

Thank you for your time.

JasonTS
  • 2,479
  • 4
  • 32
  • 48
  • possible duplicate of [Django REST Framework upload image: "The submitted data was not a file"](http://stackoverflow.com/questions/28036404/django-rest-framework-upload-image-the-submitted-data-was-not-a-file) – Kevin Brown-Silva Mar 31 '15 at 20:31

1 Answers1

0

Contrary to popular belief, it's not possible to upload files using JSON such that Django can recognize them without hacking around it. This is because JSON does not natively support file uploads, so you have to handle file serialization and uploading on your own.

But you have a few options

  • Handle file uploads separately from the metadata. This would require separate endpoints for the files and the metadata, similar to what Dropbox does with separating file uploads and the metadata.
  • Base64-encode the files when you are uploading them, and use a custom Base64FileField to handle them. drf-extras provides a Base64ImageField that can be used.
Community
  • 1
  • 1
Kevin Brown-Silva
  • 40,873
  • 40
  • 203
  • 237