2014-09-23 67 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多部分部分);如果您从未发送该内容,则服务器永远无法收到该内容。

相关问题