Saving binary data into file on model via django storages boto s3

I’m pulling back a pdf from the echosign API, which gives me the bytes of a file.

I’m trying to take those bytes and save them into a boto s3 backed FileField. I’m not having much luck.

This was the closest I got, but it errors on saving ‘speaker’, and the pdf, although written to S3, appears to be corrupt.

Here speaker is an instance of my model and fileData is the ‘bytes’ string returned from the echosign api

afile = speaker.the_file = S3BotoStorageFile(filename, "wb", S3BotoStorage())

Best answer

I’m closer!

    content = ContentFile(fileData), content)

Turns out the FileField is already a S3BotoStorage, and you can create a new file by passing the raw datadin like that. What I don’t know is how to make it binary (I’m assuming its not). My file keeps coming up corrupted, despite having a good amount of data in it.

For reference here is the response from echosign:

I’m essentially grabbing the bytes and passing it to ContentFile as fileData. Maybe I need to base64 decode. Going to try that!


That worked!

It seems I have to ask the question here before I figure out the answer. Sigh. So the final code looks something like this:

content = ContentFile(base64.b64decode(fileData)), content)