2012-10-11 2 views
1

제출할 때 couchdb 문서를 만들고 첨부 파일을 문서에 추가하는 웹 양식을 만들려고합니다. 튜토리얼/다른 포럼에서 2 단계 프로세스로이 작업을 수행해야한다는 것을 알았습니다 (futon과 마찬가지로). 업로드 할 문서를 가져올 수 있지만 첨부 파일을 업로드 할 수없는 것 같습니다.html 양식과 jquery를 통한 CouchDB 문서 첨부 파일

html 파일에 : 나는 여러 가지 방법을 시도했습니다, 현재 내가 뭔가 같이 할

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

이 자바 스크립트는 다음과 같습니다 다음

<!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 꽤 많이 futon.browse.js uploadAttachment 세그먼트에서 가져 왔습니다. dialogue.html 파일은 couchdb의 www/dialog/_upload_attachment.html을 그대로 복사 한 것입니다. 그런 다음 모든 파일 (기본 html, basic.js 및 dialogue.html)이 CouchDB 디자인 문서 (업 로더라는 데이터베이스)에 업로드됩니다.

문서가 잘 작성되었지만 내가하는 일과 관계없이 첨부 파일은 저장되지 않습니다. 여러 가지 방법 중 하나를 시도해도 여러 부분으로 구성된 양식에 대한 오류가 발생하거나이 경우 인식 할 수있는 오류가 전혀 발생하지 않습니다.

내가 뭘 잘못하고 있는지 아는 사람이 있습니까?

답변

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"); 
    } 
}; 
관련 문제