How to upload a file to a Python web server?











up vote
0
down vote

favorite












I am trying to write a basic web server in python that should be able to handle post requests with files and save it locally.



Here is my sample:



import logging    
from http.server import BaseHTTPRequestHandler, HTTPServer

class Server(BaseHTTPRequestHandler):
def _set_response(self):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()

def do_POST(self):
content_length = int(self.headers['Content-Length']) # <--- Gets the size of data
post_data = self.rfile.read(content_length) # <--- Gets the data itself
self.save_file(post_data)
self._set_response()
self.wfile.write("POST request for {}".format(self.path).encode('utf-8'))

def save_file(self, file):
output_file = open("file.saved", "wb")
output_file.write(file)
output_file.close()

def run(server_class=HTTPServer, handler_class=Server, port=8080):
server_address = ('', port)
httpd = server_class(server_address, handler_class)
try:
httpd.serve_forever()
except KeyboardInterrupt:
pass
httpd.server_close()


if __name__ == '__main__':
from sys import argv

if len(argv) == 2:
run(port=int(argv[1]))
else:
run()


The post_data that I recieve in do_POST beside the file itself contain other meta information about request itself, I can't figure it out how to to extract from post_data only binary file.



Here is example of post request that server should serve:



cURL:



curl -X POST 
http://localhost:8080/x/
-H 'Postman-Token: 69de1364-88e8-47d1-9c2e-1e0e1d634c8b'
-H 'cache-control: no-cache'
-H 'content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW'
-F 'file=@D:filesGit-2.13.3-64-bit.exe'


HTTP:



POST /x/ HTTP/1.1
Host: localhost:8080
cache-control: no-cache
Postman-Token: 3c216882-8160-4936-be7e-263cf56c7d4d
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW

Content-Disposition: form-data; name="file"; filename="D:InstallsGit-2.13.3-64-bit.exe


------WebKitFormBoundary7MA4YWxkTrZu0gW--


How do I extract from post_data variable only "Git-2.13.3-64-bit.exe" binary file and save it on disk ?










share|improve this question




























    up vote
    0
    down vote

    favorite












    I am trying to write a basic web server in python that should be able to handle post requests with files and save it locally.



    Here is my sample:



    import logging    
    from http.server import BaseHTTPRequestHandler, HTTPServer

    class Server(BaseHTTPRequestHandler):
    def _set_response(self):
    self.send_response(200)
    self.send_header('Content-type', 'text/html')
    self.end_headers()

    def do_POST(self):
    content_length = int(self.headers['Content-Length']) # <--- Gets the size of data
    post_data = self.rfile.read(content_length) # <--- Gets the data itself
    self.save_file(post_data)
    self._set_response()
    self.wfile.write("POST request for {}".format(self.path).encode('utf-8'))

    def save_file(self, file):
    output_file = open("file.saved", "wb")
    output_file.write(file)
    output_file.close()

    def run(server_class=HTTPServer, handler_class=Server, port=8080):
    server_address = ('', port)
    httpd = server_class(server_address, handler_class)
    try:
    httpd.serve_forever()
    except KeyboardInterrupt:
    pass
    httpd.server_close()


    if __name__ == '__main__':
    from sys import argv

    if len(argv) == 2:
    run(port=int(argv[1]))
    else:
    run()


    The post_data that I recieve in do_POST beside the file itself contain other meta information about request itself, I can't figure it out how to to extract from post_data only binary file.



    Here is example of post request that server should serve:



    cURL:



    curl -X POST 
    http://localhost:8080/x/
    -H 'Postman-Token: 69de1364-88e8-47d1-9c2e-1e0e1d634c8b'
    -H 'cache-control: no-cache'
    -H 'content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW'
    -F 'file=@D:filesGit-2.13.3-64-bit.exe'


    HTTP:



    POST /x/ HTTP/1.1
    Host: localhost:8080
    cache-control: no-cache
    Postman-Token: 3c216882-8160-4936-be7e-263cf56c7d4d
    Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW

    Content-Disposition: form-data; name="file"; filename="D:InstallsGit-2.13.3-64-bit.exe


    ------WebKitFormBoundary7MA4YWxkTrZu0gW--


    How do I extract from post_data variable only "Git-2.13.3-64-bit.exe" binary file and save it on disk ?










    share|improve this question


























      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      I am trying to write a basic web server in python that should be able to handle post requests with files and save it locally.



      Here is my sample:



      import logging    
      from http.server import BaseHTTPRequestHandler, HTTPServer

      class Server(BaseHTTPRequestHandler):
      def _set_response(self):
      self.send_response(200)
      self.send_header('Content-type', 'text/html')
      self.end_headers()

      def do_POST(self):
      content_length = int(self.headers['Content-Length']) # <--- Gets the size of data
      post_data = self.rfile.read(content_length) # <--- Gets the data itself
      self.save_file(post_data)
      self._set_response()
      self.wfile.write("POST request for {}".format(self.path).encode('utf-8'))

      def save_file(self, file):
      output_file = open("file.saved", "wb")
      output_file.write(file)
      output_file.close()

      def run(server_class=HTTPServer, handler_class=Server, port=8080):
      server_address = ('', port)
      httpd = server_class(server_address, handler_class)
      try:
      httpd.serve_forever()
      except KeyboardInterrupt:
      pass
      httpd.server_close()


      if __name__ == '__main__':
      from sys import argv

      if len(argv) == 2:
      run(port=int(argv[1]))
      else:
      run()


      The post_data that I recieve in do_POST beside the file itself contain other meta information about request itself, I can't figure it out how to to extract from post_data only binary file.



      Here is example of post request that server should serve:



      cURL:



      curl -X POST 
      http://localhost:8080/x/
      -H 'Postman-Token: 69de1364-88e8-47d1-9c2e-1e0e1d634c8b'
      -H 'cache-control: no-cache'
      -H 'content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW'
      -F 'file=@D:filesGit-2.13.3-64-bit.exe'


      HTTP:



      POST /x/ HTTP/1.1
      Host: localhost:8080
      cache-control: no-cache
      Postman-Token: 3c216882-8160-4936-be7e-263cf56c7d4d
      Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW

      Content-Disposition: form-data; name="file"; filename="D:InstallsGit-2.13.3-64-bit.exe


      ------WebKitFormBoundary7MA4YWxkTrZu0gW--


      How do I extract from post_data variable only "Git-2.13.3-64-bit.exe" binary file and save it on disk ?










      share|improve this question















      I am trying to write a basic web server in python that should be able to handle post requests with files and save it locally.



      Here is my sample:



      import logging    
      from http.server import BaseHTTPRequestHandler, HTTPServer

      class Server(BaseHTTPRequestHandler):
      def _set_response(self):
      self.send_response(200)
      self.send_header('Content-type', 'text/html')
      self.end_headers()

      def do_POST(self):
      content_length = int(self.headers['Content-Length']) # <--- Gets the size of data
      post_data = self.rfile.read(content_length) # <--- Gets the data itself
      self.save_file(post_data)
      self._set_response()
      self.wfile.write("POST request for {}".format(self.path).encode('utf-8'))

      def save_file(self, file):
      output_file = open("file.saved", "wb")
      output_file.write(file)
      output_file.close()

      def run(server_class=HTTPServer, handler_class=Server, port=8080):
      server_address = ('', port)
      httpd = server_class(server_address, handler_class)
      try:
      httpd.serve_forever()
      except KeyboardInterrupt:
      pass
      httpd.server_close()


      if __name__ == '__main__':
      from sys import argv

      if len(argv) == 2:
      run(port=int(argv[1]))
      else:
      run()


      The post_data that I recieve in do_POST beside the file itself contain other meta information about request itself, I can't figure it out how to to extract from post_data only binary file.



      Here is example of post request that server should serve:



      cURL:



      curl -X POST 
      http://localhost:8080/x/
      -H 'Postman-Token: 69de1364-88e8-47d1-9c2e-1e0e1d634c8b'
      -H 'cache-control: no-cache'
      -H 'content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW'
      -F 'file=@D:filesGit-2.13.3-64-bit.exe'


      HTTP:



      POST /x/ HTTP/1.1
      Host: localhost:8080
      cache-control: no-cache
      Postman-Token: 3c216882-8160-4936-be7e-263cf56c7d4d
      Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW

      Content-Disposition: form-data; name="file"; filename="D:InstallsGit-2.13.3-64-bit.exe


      ------WebKitFormBoundary7MA4YWxkTrZu0gW--


      How do I extract from post_data variable only "Git-2.13.3-64-bit.exe" binary file and save it on disk ?







      python web-services http file-upload multipartform-data






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 20 at 15:06

























      asked Nov 20 at 15:00









      dev devv

      2016




      2016





























          active

          oldest

          votes











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53395794%2fhow-to-upload-a-file-to-a-python-web-server%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown






























          active

          oldest

          votes













          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes
















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53395794%2fhow-to-upload-a-file-to-a-python-web-server%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          404 Error Contact Form 7 ajax form submitting

          How to know if a Active Directory user can login interactively

          Refactoring coordinates for Minecraft Pi buildings written in Python