2014-09-23 68 views
0

我試圖得到一個非常基本的文件上傳功能工作,並在完全損失發現我做錯了什麼。大部分代碼來自SE。現在所有發佈到服務器的方式都是'[FormData]',它是一個文本字符串,而不是一個對象。如何解決此文件上傳代碼?

HTML表單:

<form id="add-torr" action="/transmission/to_client2" enctype="multipart/form-data" method="post"class="form-inline pull-right"> 
     <input id="torr-files" type="file" size="30"style="color:#000; background:#ddd" multiple /> 
     <button id="add-torr-button" type="submit" class="btn btn-primary upload">Upload</button> 
    </form> 

的JS:

var form = document.getElementById('add-torr'); 
form.onsubmit = function(upload){ 
    upload.preventDefault(); 
    var uploadButton = document.getElementById('upload-torr-button'); 
    var data = new FormData(); 
    jQuery.each($('#torr-files')[0].files, function(i, file) { 
     data.append('file-'+i, file); 
     //alert(data); 
    }); 
    //alert($('#torr-files').val.text); 
    $.ajax({ 
     url: '/transmission/to_client2/' + data, 
     //data: data, 
     dataType: 'text', 
     cache: false, 
     contentType: false, 
     processData: false, 
     type: 'POST', 
     success: function(response){ 
      alert(response); 
     }, 
     error: function(){ 
      alert("error in ajax form submission"); 
     } 
    }); 
}; 

的Python代碼:

#For torrent upload have to be base 64 encode 
@cherrypy.expose() 
@cherrypy.tools.json_out() 
def to_client2(self, info): 
    print 'info: ', info 
    try: 
     self.logger.info('Added torrent info to Transmission from file') 
     return self.fetch('torrent-add', {'metainfo': info}) 
    except Exception as e: 
     self.logger.error('Failed to add torrent %s file to Transmission %s' % (info, e)) 

我知道有噸的例子,但我需要一些額外的眼球告訴我我的代碼有什麼問題。請幫助?

回答

0

你只需添加FormData對象本身的網址:

url: '/transmission/to_client2/' + data, 

在JavaScript中,當你添加一個字符串和其他一些物體,它會調用該對象的toString方法。沒有toString方法的對象將返回類似[object MyPrototype]的內容。

這裏真的沒有辦法。您不能將「傳遞對象」作爲URL的一部分,因爲URL只是字符串。如果要將表單數據作爲URL的一部分傳遞,則必須將其編碼到查詢字符串中(如?key1=value1&key2=value2&…),並將添加到URL中。

無論如何,即使您解決了這個問題,我希望您不要指望只是將文件名添加到查詢字符串中,並且使沒有內容的POST將要上載文件。您必須以某種方式將文件內容附加到請求中(例如,作爲MIME多部分部分);如果您從未發送該內容,則服務器永遠無法收到該內容。

相關問題