2013-07-13 25 views
1

我想创建时将文件附加到CouchDB文档。CouchDB,Kanso,文件上传错误

这是HTML代码:

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

这是JS代码处理上传

$(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'); 
    }); 

}); 

这将产生以下错误消息500:

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

我使用带有kanso 0.2.2和db 0.1.0的CouchDB 1.3.1。

回答

1

好吧我想我已经想通了。我的两个假设证明是根本错误的。首先,仅使用名为_attachments的输入字段不能上载附件。其次,CouchDB似乎不接受文件,除非它们应该附加到的文档已经存在。 (我可能是错在这一个,但它并没有为我工作。)

下面是对我的作品的解决方案:

$(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); 
     } 
     }); 

    } 
); 
}); 

这种方法需要以下两个插件: