将文件作为JSON上载到Python Web服务器 [英] Upload file as JSON to Python webserver

查看:388
本文介绍了将文件作为JSON上载到Python Web服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to upload a file as JSON from the client to a Python webserver (Tornado) and save it on the server. This is my simplified setup:

客户端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服务器:

Python Webserver:

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()

  1. 所有上传的文件都是空的(PDF中为空白页,不支持JPG"文件类型,无法打开Word文件),并且其大小几乎是原始文件的两倍.我该如何解决?
  2. 是否可以改善此设置?

推荐答案

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

You are trying to upload binary files (word, jpg), serialised as JSON, and store them on the server.

要处理JSON中的二进制数据,请先将二进制数据编码为base64 ,然后调用JSON.stringify.

To handle binary data in JSON, encode the binary data as base64 first, then call 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并以二进制

On the server side, you need to deserialise from JSON, decode the base64 and the open a file in binary mode to ensure that what you are writing to disk is the uploaded binary data. Opening the file in text mode requires that the data be encoded before writing to disk, and this encoding step will corrupt binary data.

类似的事情应该起作用:

Something like this ought to work:

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)

这篇关于将文件作为JSON上载到Python Web服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆