【问题标题】:CouchDB document attachments via html form and jquery通过 html 表单和 jquery 的 CouchDB 文档附件
【发布时间】:2012-10-11 09:11:11
【问题描述】:

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

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 的数据库中)。

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

有谁知道我做错了什么?

【问题讨论】:

    标签: javascript jquery ajax couchdb


    【解决方案1】:

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

     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");
        }   
    };
    

    【讨论】:

      猜你喜欢
      • 2013-11-05
      • 1970-01-01
      • 2012-01-08
      • 2016-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多