-1

I'm posting this because it was so difficult to find the information for my use case in one single place. The original Task sounded simple: "How do I upload a file selected through an file type input tag on a web page to a simple http server able to parse POST requests?". Unfortunately I spent several days looking for material that would help without forcing me to use forms.

Li Brary
  • 59
  • 9

1 Answers1

0

I would like to offer what I discovered in the end to do this, and hopefully it will help others.

Helpful info taken from File Upload without Form https://blog.anvileight.com/posts/simple-python-http-server/ https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

cheers


index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title></title>
  <script src="test.js"></script>
</head>
<body>
    <input type="file" name="fileload">
    <button id="bttn">submit</button>
</body>
</html>

test.js

let run = ()=> {let inpt = document.querySelector("input")
  let f
  inpt.onchange =()=> {
    f = inpt.files[0]
  }
  let btn = document.querySelector("#bttn")
  btn.addEventListener("click",()=> {
    console.log("clc")
    let xmlHttpRequest = new XMLHttpRequest();

    let fileName = f.name
    let target = "http://localhost:8080"
    let mimeType = "text/csv"

    //xmlHttpRequest.open('POST', target, true);
    //xmlHttpRequest.setRequestHeader('Content-Type', mimeType);
    //xmlHttpRequest.setRequestHeader('Content-Disposition', 'attachment; filename="' + fileName + '"');
    //xmlHttpRequest.send(f);
    fetch("http://localhost:8080",{
      method:"POST",
      mode:"cors",
      headers:{
        "Content-type":"text/csv",
        "Content-disposition":`attachment;filename=${fileName}`
      },
      body:f
    }).then(
      res=> {
        console.log(res)  
        res.text()
      }
    ).then(text=> console.log(text))
  })
}
window.onload = ()=> {
  run()
}

pyserv.py

from http.server import HTTPServer, SimpleHTTPRequestHandler

from io import BytesIO


class TestingRequestHandler(SimpleHTTPRequestHandler):
    def do_GET(self):
        super().do_GET()
    def do_POST(self):
        print("--- headers \n{} ---".format(self.headers))
        print("whole self --\n{}--".format(self))
        content_length = int(self.headers['Content-Length'])
        print(self.rfile,"is rfile")
        body = self.rfile.read(content_length)
        print("body is ",body)
        self.send_response(200)
        self.end_headers()
        response = BytesIO()
        response.write(b'This is POST request. ')
        response.write(b'Received: ')
        response.write(body)
        self.wfile.write(response.getvalue())


httpd = HTTPServer(('localhost', 8080), TestingRequestHandler)
httpd.serve_forever()
Li Brary
  • 59
  • 9