1

I'm trying to attach files to CouchDB documents when they are created.

This is the HTML code:

<form>
  <input type="hidden" name="type" value="devtest"/>
  <input type="file" name="_attachments" id="picture" accept="image/*" multiple/>
  <button type="submit">Go</button>
</form>

This is the JS code handling the upload

$(document).on('submit', 'form', function(e) {

  e.preventDefault();

  var formdata = $(this).serializeObject(); // Provided by a pluign

  $(this).find(':file').each(function(k,v) {
    formdata[$(this).attr('name')] = $(this).val(); // Treating files
  });

  // Using the kanso db package
  m.db.current().saveDoc(
    formdata,
    function(err,res) {
      console.log('gna');
    });

});

This produces the following error 500 message:

{"error":"doc_validation","reason":"Bad special document member: _attachments"}

I'm using CouchDB 1.3.1 with kanso 0.2.2 and db 0.1.0.

1 Answers1

1

Alright I think I've figured it out. Two assumptions of mine proved to be fundamentally wrong. First, attachments can't be uploaded using just an input field named _attachments. Second, CouchDB doesn't seem to accept files unless the document to which they should be attached exists already. (I could be wrong on this one, but it doesn't work for me.)

Here's the solution that works for me:

$(document).on('submit', '#userctl form', function(e) {

  e.preventDefault()
  var data = $(this).serializeObject();

  // Use the Kanso API to create a normal document without attachments
  m.db.current().saveDoc(
    data,
    function(err,res) {

      // Use ajaxSubmit provided by the jquery.forms plugin to submit the attachments
      $('#userctl form').ajaxSubmit({
        url:  m.db.current().url + '/' + res.id,
        data: {
          _rev: res.rev // Provide a revision, otherwise the upload fails
        },
        success: function(res) {
          console.log(res);
        }
      });

    }
  );
});

This approach requires the following two plugins: