-5

There is a client sending a file object in JavaScript. There is a server written in Python. Please have a look following code of both client and server.

Client(JavaScript):

function sendFile(file) {
  fetch('http://localhost:8088', {
     method: 'POST',
     body: JSON.stringify({
       name: "file",
       code: file
     })
   })
   .then(res => {
     // handle response
     var reader = res.body.getReader();
     reader.read()
     .then(({done, value}) => {
       // need to check done
       let chunks = new Uint8Array(value.length);
       chunks.set(value, 0);
       let result = new TextDecoder("utf-8").decode(chunks);
       console.log(result);
    });
  })
  .catch(err => {
    // handle error
    console.log('fetch error:', err);
  });
}

document.getElementById('sendBtn').addEventListener('change',
 ()=>{this.sendFile(document.getElementById('fileInput').files[0]);});

Server(Python):

#!/usr/bin/python
import BaseHTTPServer
import json

class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler):
       def do_POST(self):
          length = int(self.headers.getheader('content-length'))
          body = self.rfile.read(length)
          self.send_response(200)
          self.send_header('Access-Control-Allow-Origin', '*')
          self.end_headers()
          self.wfile.write("post response")
          data = json.loads(body)

          # print data['file'] just returns '{ }'
          # I would like to save this file on sever side.
          # Is it possible??

server = BaseHTTPServer.HTTPServer(("localhost", 8088), MyHandler)
server.serve_forever()
  

I would like to want to know if there is a way to read file object written in javascript on python world.

cnook
  • 117
  • 12
  • The question is unclear to me. However, if it is a json you can load the json directly into python code (as a dictionary) using `import json`. See https://docs.python.org/3/library/json.html – sudhish Jan 01 '21 at 13:46
  • It seems that I need to send file data not a file. So Python server got empty { }. I found https://stackoverflow.com/questions/24139216/how-can-i-serialize-an-input-file-object-to-json Now I need to find out how save the data to a file on Python server side. – cnook Jan 04 '21 at 03:32
  • And finally I could save image data with https://stackoverflow.com/questions/33870538/how-to-parse-data-uri-in-python/33870677 – cnook Jan 04 '21 at 06:01

1 Answers1

0

I had to send file content How can I serialize an input File object to JSON?

And it is able to read and save it using dcodestring How to parse data-uri in python?

Thank you all.

cnook
  • 117
  • 12