create a http server and upload a file and return a json response in python

Here's an example code that creates an HTTP server that accepts file uploads and returns a JSON response:

import http.server
import json
import urllib.parse

class UploadHandler(http.server.BaseHTTPRequestHandler):
    def do_POST(self):
        content_type = self.headers['Content-Type']
        if content_type.startswith('multipart/form-data'):
            # Parse the multipart/form-data content
            form_data = http.server.parse_multipart(self.rfile, self.headers)
            uploaded_file = form_data[b'file']

            # Do something with the file
            filename = uploaded_file.filename.decode('utf-8')
            with open(filename, 'wb') as f:
                f.write(uploaded_file.getvalue())

            # Return a JSON response
            response = {'message': 'File uploaded successfully'}
            self.send_response(200)
            self.send_header('Content-Type', 'application/json')
            self.end_headers()
            self.wfile.write(json.dumps(response).encode('utf-8'))
        else:
            self.send_response(400)
            self.send_header('Content-Type', 'application/json')
            self.end_headers()
            response = {'message': 'Invalid content type'}
            self.wfile.write(json.dumps(response).encode('utf-8'))

httpd = http.server.HTTPServer(('localhost', 8000), UploadHandler)
httpd.serve_forever()
1282 chars
33 lines

This code listens on port 8000 and accepts HTTP POST requests with the multipart/form-data content type. When a file is uploaded, it is saved to the current directory and a JSON response with a success message is returned. If the content type is not multipart/form-data, a 400 Bad Request with an error message is returned.

gistlibby LogSnag