title: Python - HTTP multipart/form-data POST request
body: <p>I would like to upload a file to a web server. From what I have read, the best way to do this is to use the multipart/form-data encoding type on an HTTP POST request.</p>
  
  <p>My research seems to indicate that there is no simple way to do this using the Python standard library. I am using Python 3.</p>
  
  <p>(Note: see a package called <a href="http://docs.python-requests.org/en/latest/" rel="noreferrer">requests</a> (<a href="https://pypi.python.org/pypi/requests" rel="noreferrer">PyPI Link</a>) to easily accomplish this)</p>
  
  <p>I am currently using this method:  </p>
  
  <pre><code>import mimetypes, http.client
  boundary = 'wL36Yn8afVp8Ag7AmP8qZ0SA4n1v9T' # Randomly generated
  for fileName in fileList:
      # Add boundary and header
      dataList.append('--' + boundary)
      dataList.append('Content-Disposition: form-data; name={0}; filename={0}'.format(fileName))
  
      fileType = mimetypes.guess_type(fileName)[0] or 'application/octet-stream'
      dataList.append('Content-Type: {}'.format(fileType))
      dataList.append('')
  
      with open(fileName) as f: 
          # Bad for large files
          dataList.append(f.read())
  
  dataList.append('--'+boundary+'--')
  dataList.append('')
  contentType = 'multipart/form-data; boundary={}'.format(boundary)
  
  body = '\r\n'.join(dataList)
  headers = {'Content-type': contentType}
  
  conn = http.client.HTTPConnection('http://...')
  req = conn.request('POST', '/test/', body, headers)
  
  print(conn.getresponse().read())
  </code></pre>
  
  <p>This works to send text.</p>
  
  <p>There are two issues: This is text only, and the whole text file must be stored in memory as a giant string.</p>
  
  <p>How can I upload any binary file?  Is there a way to do this without reading the whole file into memory?</p>