Skip to content

Instantly share code, notes, and snippets.

@PyYoshi
Created May 23, 2011 13:47
Show Gist options
  • Save PyYoshi/986711 to your computer and use it in GitHub Desktop.
Save PyYoshi/986711 to your computer and use it in GitHub Desktop.
multipart form-dataで画像ファイルをアップするとき。
def _enc_image(filename, max_size):
try:
if os.path.getsize(filename) > (max_size * 1024):
print 'File is too big, must be less than %d' % (max_size * 1024)
except os.errno, e:
print 'Unable to access file, %s' % e
file_type = mimetypes.guess_type(filename)
if file_type is None:
print 'Could not datermine file type'
file_type = file_type[0]
if file_type not in ['image/gif', 'image/jpeg', 'image/png']:
print 'Invalid file type for image: %s' % filename
fp = open(filename, 'rb')
BOUNDARY = 'IlOvEpYtHoN'
body = []
body.append('--' + BOUNDARY)
body.append('Content-Disposition: form-data; name="image"; filename="%s"' % filename)
body.append('Content-Type: %s' % file_type)
body.append('')
body.append(fp.read())
body.append('--' + BOUNDARY + '--')
body.append('')
fp.close()
body = '\r\n'.join(body)
headers = {
'Content-Type': 'multipart/form-data; boundary=%s' % BOUNDARY,
'Content-Length': len(body)
}
return headers, body
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment