2

urllib2 を使用してバイナリ データを含むファイルをサーバーに送信したい:

def encode_multipart_formdata(fields, files):
    LIMIT = '----------lImIt_of_THE_fIle_eW_$'
    CRLF = '\r\n'
    L = []
    for (key, value) in fields:
        L.append('--' + LIMIT)
        L.append('Content-Disposition: form-data; name="%s"' % key)
        L.append('')
        L.append(str(value))
    for (key, filename, value) in files:
        L.append('--' + LIMIT)
        L.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key,    str(filename)))
        L.append('Content-Type: %s' % get_content_type(filename))
        L.append('')
        L.append(value)
    L.append('--' + LIMIT + '--')
    L.append('')
    body = CRLF.join(L)
    content_type = 'multipart/form-data; boundary=%s' % LIMIT
    return content_type, body

使用:

    f = open(filePath, "rb")
    content_type, body = encode_multipart_formdata([("param1",self.param1)], [("myfile", self.name, f.read())])
    request = urllib2.Request(url, body)
    request.add_header('Content-type', content_type)
    request.add_header('Content-length', str(len(body)))
    response =  urllib2.urlopen(request)

ファイルにASCIIシンボルのみが含まれている場合は、すべて問題ありません。しかし、ファイルにバイナリデータが含まれている場合、コードの最後の文字列でエラーが発生します:

UnicodeDecodeError: 'ascii' codec can't decode byte 0x9a in position 271: ordinal not in range(128)

ボディをエンコードする方法は? サーバーとクライアントのファイルは同じである必要があります

4

1 に答える 1