我试图得到一个非常基本的文件上传功能工作,并在完全损失发现我做错了什么。大部分代码来自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))
我知道有吨的例子,但我需要一些额外的眼球告诉我我的代码有什么问题。请帮助?