| 338 | |
| 339 | |
| 340 | def encode_file(boundary, key, file): |
| 341 | def to_bytes(s): |
| 342 | return force_bytes(s, settings.DEFAULT_CHARSET) |
| 343 | |
| 344 | # file.name might not be a string. For example, it's an int for |
| 345 | # tempfile.TemporaryFile(). |
| 346 | file_has_string_name = hasattr(file, "name") and isinstance(file.name, str) |
| 347 | filename = os.path.basename(file.name) if file_has_string_name else "" |
| 348 | |
| 349 | if hasattr(file, "content_type"): |
| 350 | content_type = file.content_type |
| 351 | elif filename: |
| 352 | content_type = mimetypes.guess_type(filename)[0] |
| 353 | else: |
| 354 | content_type = None |
| 355 | |
| 356 | if content_type is None: |
| 357 | content_type = "application/octet-stream" |
| 358 | filename = filename or key |
| 359 | return [ |
| 360 | to_bytes("--%s" % boundary), |
| 361 | to_bytes( |
| 362 | 'Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename) |
| 363 | ), |
| 364 | to_bytes("Content-Type: %s" % content_type), |
| 365 | b"", |
| 366 | to_bytes(file.read()), |
| 367 | ] |
| 368 | |
| 369 | |
| 370 | class RequestFactory: |