Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/309.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将带有javascript WebSocket的文件上载到python tornado服务器_Javascript_Python_Websocket_Tornado_Filereader - Fatal编程技术网

将带有javascript WebSocket的文件上载到python tornado服务器

将带有javascript WebSocket的文件上载到python tornado服务器,javascript,python,websocket,tornado,filereader,Javascript,Python,Websocket,Tornado,Filereader,我试图上传一个带有javascript的文件,并通过WebSocket将数据发送到python tornado服务器。我以为这是工作的文件创建和存储在我的服务器上的机器,但当我试图打开新创建的文件,它是损坏的。 有谁能解释一下用javascript读取文件的最佳方式,以及在服务器端接收到数据后如何保存这些数据 以下是我用于加载文件的函数: HomeView.prototype.loadFile = function(dataTransfer) { var that = this;

我试图上传一个带有javascript的文件,并通过WebSocket将数据发送到python tornado服务器。我以为这是工作的文件创建和存储在我的服务器上的机器,但当我试图打开新创建的文件,它是损坏的。 有谁能解释一下用javascript读取文件的最佳方式,以及在服务器端接收到数据后如何保存这些数据

以下是我用于加载文件的函数:

 HomeView.prototype.loadFile = function(dataTransfer)
 {
    var that = this;
    var filereader = new FileReader();
    filereader.file = dataTransfer.files[0];
    that.fileName = dataTransfer.files[0].name;
    filereader.onload = function(e) {
        // file is loaded now add it to the zip file
        that.fileData = e.target.result;
   }
  // load the file
  filereader.readAsBinaryString(dataTransfer.files[0]);
}
使用ws.send(JSON.stringify(msg))发送;其中msg是一个json对象,包含我的文件和消息类型。例如{data:filedata,type:fileupload} 然后,我的python服务器接收文件(data_str)并将其传递给以下函数以保存它。我在这里使用xlsx文件类型作为示例。通常情况下,我会解析文件名并存储上传时的确切文件

 def save_file_from_data(self, data_str):
    """save the rubric file for a byte string"""
    try:
        # name the zip, open in binary mode 
        fh = open("newfile.xlsx", 'wb')
        # save file data after encoding in UTF-8 first
        fh.write(data_str.encode('utf-8'))
        fh.close() 
    except:
        print("error")
在写入文件时,我也尝试过fh.write(字节(data_str,'UTF-8'))

如有任何建议或提示,将不胜感激


KB

似乎只有.xlsx文件是问题所在(来自我测试的不同类型,.txt.html.xml.py.js)。有人知道它们为什么有问题吗?
.xlsx
是一种二进制文件格式;其他的都是文本。JSON不能直接包含二进制数据;在用json包装文件时,您是否对其进行编码(例如,使用base64)?写入文件时,应使用字节而不是字符;在这一点上没有必要提及“utf8”。啊,我明白了。。谢谢,这真让我困惑!发送时我正在使用JSON.stringify(),但现在我知道如何修复它,再次感谢!