我試圖得到一個非常基本的文件上傳功能工作,並在完全損失發現我做錯了什麼。大部分代碼來自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))
我知道有噸的例子,但我需要一些額外的眼球告訴我我的代碼有什麼問題。請幫助?