CouchDB文档附件通过html表单和jquery

时间:2012-10-11 09:11:12

标签: javascript jquery ajax couchdb

我正在尝试创建Web表单,在提交时将创建一个couchdb文档并将附件添加到doc。我从教程/其他论坛中看到,有必要通过两个阶段的过程来做到这一点(就像蒲公一样)。我可以上传文档,但似乎无法上传附件。我尝试了很多方法,目前我做了类似的事情:

html文件:

<!DOCTYPE HTML>
<html>
  <head>
    <title>Document submission</title>
    <style type="TEXT/CSS" media="all">
    </style>
  </head>
  <body>
    <table>
      <form id="form" name="form" action="">
        <tr>
          <td>Field</td>
            <td><input type="text" required="required" name="field">
              <span id="required">*</span></td>
        </tr><tr>
        </tr><tr>
          <td></td><td><button type="button" id="submit">Select Attachment</button><td>
        </tr>
      </form>
    </table>
  </body> 
  <script src="/_utils/script/json2.js"></script>
  <script src="/_utils/script/jquery.js"></script>
  <script src="/_utils/script/jquery.couch.js"></script>
  <script src="/_utils/script/jquery.form.js"></script>
  <script src="/_utils/script/jquery.dialog.js"></script>
  <script type="text/javascript" src="basic.js"></script>
</html>

然后使用名为basic.js的文件:

function create_document(){
    var db_name = 'uploader';
    var db = $.couch.db(db_name);
    var data={}
    data['fname']=document.form.field.value;
    db.saveDoc(data, {
        success: function (data) {
            add_attachment(db,data);
        },
        error: function () {
            alert("Cannot save the thread.");
        }
    });
}

function add_attachment(db,data){
    var docID = data.id;
    var dbName = db.name;
    var form = $("#upload-form");
    $.showDialog("dialogue.html", {
        load: function(elem) {
            $("input[name='_rev']", elem).val(data._rev);
        },
        submit: function(data, callback) {
            if (!data._attachments || data._attachments.length == 0) {
                callback({_attachments: "Please select a file to upload."});
                return;
            }
            var form = $("#upload-form");
            form.find("#progress").css("visibility", "visible");
            form.ajaxSubmit({
                url: db.uri + $.couch.encodeDocId(docID),
                success: function(resp) {
                    form.find("#progress").css("visibility", "hidden");
                    location.href = "?" + encodeURIComponent(dbName) +
                        "/" + $.couch.encodeDocId(docID);
                }
            });
        }
    });
}


$(document).ready(function() {
    $("button#submit").click(function(event) {
        create_document();
    });
});           

这个javascript几乎取自futon.browse.js uploadAttachment段。 dialog.html文件也只是couchdb的www / dialog / _upload_attachment.html的直接副本。然后将所有文件(主html,basic.js和dialog.html)上传到CouchDB设计文档(在名为uploader的数据库中)。

文档创建得很好,但无论我做什么,都不会保存附件。我尝试过的各种方法都会导致多部分表单出错,或者在这种情况下,根本没有明显的错误。

有谁知道我做错了什么?

1 个答案:

答案 0 :(得分:2)

我继承了这段代码,所以我不知道它是否是最佳的。但它确实有效:

 jQuery.fn.sendForm = function(itemID, itemType) {

    // Get all of the values from the form fields
    var itemTitle = $('.settingsForm input#title').val(),
        itemAuthor = $('.settingsForm input#author').val(),
        itemDescription = $('.settingsForm textarea#description').val(),
        itemDate = $('.settingsForm input#date').val(),
        itemRev = $('.settingsForm input#_rev').val(),
        itemDelete = $('.settingsForm input#delete:checked').val(),
        itemType = $('.settingsForm select').val(),
        itemFilename = $('.settingsForm input:file').val(); 

    // Check for new uploaded file
    if (itemFilename == undefined || itemFilename == ""){
        $('.settingsForm input:file').remove();
        itemFilename = "";
    }
    else {
        itemFilename = itemFilename.replace(/^C:\\fakepath\\/i, '');
    }


     // If no new file, then fall back on the old filename
    if (!itemFilename || itemFilename.length == 0) {
        itemFilename = $('.settingsForm input#filename').val();
    }

    // Force to add a title (the only required field)
    if (!itemTitle || itemTitle.length == 0) {
        alert(libLang.addTitle); // Get text for language
        return;
    }

    // Check if size of db is above the limit
    dbSize = maxDBSize;
    $.ajax({
        url: "/"+ homeURL,
        dataType: 'json',
        async: false,
        success: function(dbInfo){
            dbSize = dbInfo.data_size;
        }
    });
    if (itemDelete != 'Yes' && dbSize >= maxDBSize){
        alert(libLang.noSpace);
        return;
    }




    if (itemDelete != 'Yes'){

        if (itemID != 'add'){

            // Update existing record
            $(this).ajaxSubmit({
                url: "/"+ homeURL +"/"+ itemID,
                data: {"filename":itemFilename},
                success: function(resp) {

                    $.getJSON("/"+ homeURL +"/"+ itemID, function(revData) {
                        itemRev = revData._rev;
                        itemAttachment = revData._attachments;
                        user = revData.user;

                        if (!revData._attachments || revData._attachments.length == 0) {

                            $.couch.db(homeURL).saveDoc({
                                "_id": itemID,
                                "_rev": itemRev,
                                "filename":itemFilename,
                                "title":itemTitle,
                                "author":itemAuthor,
                                "type":itemType,
                                "description":itemDescription,
                                "date":itemDate,
                                "user":user
                            }, {
                                success: function() { 
                                    alert(libLang.saved); // Get text for language
                                    window.location.replace("index.html");
                                }
                            });
                        }
                        else {
                            $.couch.db(homeURL).saveDoc({
                                "_id": itemID,
                                "_rev": itemRev,
                                "filename":itemFilename,
                                "title":itemTitle,
                                "author":itemAuthor,
                                "type":itemType,
                                "description":itemDescription,
                                "date":itemDate,
                                "user":user,
                                "_attachments":itemAttachment
                            }, {
                                success: function() { 
                                    alert(libLang.saved); // Get text for language
                                    window.location.replace("index.html");
                                }
                            });
                        };
                    });
                }
            });
        } 
        else {


            // Add new record
            uniqueID = $.couch.newUUID();
            itemID = itemTitle.replace(/[\s]/g,'_');
            itemID = homeUser +'-'+ itemType.charAt(0).toUpperCase() + itemType.slice(1) +'-'+  encodeURI(itemID) +'-'+ uniqueID;
            itemID = itemID.replace(/[^a-z 0-9 _ -]+/gi,'');


            $('form .settingsForm').attr({"action":"/"+ homeURL +"/"+ itemID});

            // Save information
            $.couch.db(homeURL).saveDoc({
                "_id": itemID,
                "filename":itemFilename,
                "title":itemTitle,
                "author":itemAuthor,
                "type":itemType,
                "description":itemDescription,
                "date":itemDate,
                "user":homeUser
            }, {
                success: function(){

                    // Get saved info, then add attachment to item
                    $.getJSON("/"+ homeURL +"/"+ itemID, function(revData) {

                        $('.settingsForm input#_rev').val(revData._rev);

                        var data = {};

                        $.each($("form :input").serializeArray(), function(i, field) {
                            data[field.name] = field.value;
                        });

                        $("form :file").each(function() {
                            data[this.name] = this.value.replace(/^C:\\fakepath\\/g, ''); // file inputs need special handling
                        });

                        itemFilename = data._attachments;


                        $('form.settingsForm').ajaxSubmit({
                            url: "/"+ homeURL +"/"+ itemID,
                            success: function(resp) {
                                $.getJSON("/"+ homeURL +"/"+ itemID, function(saveData) {
                                    itemRev = saveData._rev;
                                    itemAttachment = saveData._attachments;

                                    // Resave all information
                                    $.couch.db(homeURL).saveDoc({
                                        "_id": itemID,
                                        "_rev": itemRev,
                                        "filename":itemFilename,
                                        "title":itemTitle,
                                        "author":itemAuthor,
                                        "type":itemType,
                                        "description":itemDescription,
                                        "date":itemDate,
                                        "user":homeUser,
                                        "_attachments":itemAttachment
                                    }, {
                                        success: function() { 
                                            alert(libLang.saved); // Get text for language
                                            window.location.replace("index.html");
                                        }
                                    });
                                });
                            }
                        });
                    });
                }
            });         
        };          
    } else {
        // Delete the item from the library
        $.couch.db(homeURL).removeDoc({'_id': itemID, "_rev": itemRev});
        window.location.replace("index.html");
    }   
};