将文件作为JSON上载到Python Web服务器 - javascript

我想将文件作为JSON从客户端上传到Python网络服务器(Tornado)并将其保存在服务器上。这是我的简化设置:

客户端HTML:

<input type="file" id="myFile" onchange="fileChange" />

客户端JS:

function fileChange(event) {
    const file = event.target.files[0];
    const fileReader = new FileReader();
    fileReader.onload = (e) => uploadFile(e.target.result, file.name);
    fileReader.readAsText(file);
}

function uploadFile(fileContent, fileName) {
    const data = {fileContent, fileName};
    axios.post('http://localhost:8080/api/uploadFile', JSON.srtingify(data));
}

Python Web服务器:

class UploadFileHandler(tornado.web.RequestHandler):

    def post(self):
        requestBody = tornado.escape.json_decode(self.request.body)
        file = open(requestBody["fileName"], "w+")
        file.write(requestBody["fileContent"].encode("UTF-8"))
        file.close()

所有上传的文件都是空的(PDF中为空白页,“不支持JPG”文件类型,无法打开Word文件),并且其大小几乎是原始文件的两倍。我怎样才能解决这个问题?
有没有办法改善此设置?

参考方案

您正在尝试上传二进制文件(word,jpg),将其序列化为JSON,并将其存储在服务器上。

要处理JSON中的二进制数据,请先encode the binary data as base64,然后调用JSON.stringify

像这样(未经测试):

function uploadFile(fileContent, fileName) {
    // Encode the binary data to as base64.
    const data = {
        fileContent: btoa(fileContent),
        fileName: fileName
    };
    axios.post('http://localhost:8080/api/uploadFile', JSON.stringify(data));
}

在服务器端,您需要从JSON反序列化,解码base64并打开二进制文件mode中的文件,以确保要写入磁盘的是上传的二进制数据。以文本模式打开文件要求在写入磁盘之前对数据进行编码,并且此编码步骤将破坏二进制数据。

这样的事情应该起作用:

class UploadFileHandler(tornado.web.RequestHandler):

    def post(self):
        requestBody = tornado.escape.json_decode(self.request.body)
        # Decode binary content from base64
        binary_data = base64.b64decode(requestBody[fileContent])
        # Open file in binary mode
        with open(requestBody["fileName"], "wb") as f:
            f.write(binary_data)

Mongo汇总 - javascript

我的收藏中有以下文件{ "_id": ObjectId("54490b8104f7142f22ecc97f"), "title": "Sample1", "slug": "samplenews", "cat": …

如何从客户端将数据插入数据库? - javascript

我是Web开发的初学者,可以访问cpanel上托管的网站,并且需要对其进行一些更改。这个网站的后端是由蛋糕PHP制作的,我想使用ajax从客户端将一些数据插入其数据库。问题是我不知道如何获取负责插入数据库的PHP文件的URL。参见下面的代码:var xhttp = newXMLHttpRequest(); xhttp.onreadystatechange= …

编码JSON数据以保留json格式 - javascript

由于JSON值是动态生成的,并且其中的值是基于用户输入的,因此,如果用户在字符串中输入了不可接受的字符(如"),则会使json无效。就像是:{ "tag" : "demo", "value": "user " input" } 有没有一种方法可以编码或转义JS…

执行onclick时获得意外令牌 - javascript

我正在使用onclick事件从PHP调用JS函数。这是我的代码:我在一个函数中,因此我需要通过PHP来完成它,因为然后我会返回:$html = '<input type="checkbox" checked value="1" id="setGetSku" name="se…

在JavaScript中运行方法C# - javascript

打扰一下,我有这种C#asp方法。受保护的无效btnSave_Click(对象发送者,EventArgs e)有谁知道我该如何发送脚本给您?可以办到?。 javascript大神给出的解决方案 是的,那可以做到。为此,您在.aspx.cs页中创建了函数,然后单击保存按钮上的代码将其复制到函数中,然后执行以下步骤。//Call cs method from J…