Send file via JSON instead of uploading to server, Django
<p>I have an app that currently allows a user to upload a file and it saves the file on the web server. My client has now decided to use a third party cloud hosting service for their file storage needs. The company has their own API for doing CRUD operations on their server, so I wrote a script to test their API and it sends a file as a base64 encoded JSON payload to the API. The script works fine but now I'm stuck on how exactly how I should implement this functionality into Django.</p>

<p>json_testing.py</p>

<pre><code>import base64
import json
import requests
import magic

filename = 'test.txt'

# Open file and read file and encode it as a base64 string
with open(filename, "rb") as test_file:
    encoded_string = base64.b64encode(test_file.read())

# Get MIME type using magic module
mime = magic.Magic(mime=True)
mime_type = mime.from_file(filename)

# Concatenate MIME type and encoded string with string data
# Use .decode() on byte data for mime_type and encoded string
file_string = 'data:%s;base64,%s' % (mime_type.decode(), encoded_string.decode())
payload = {
    "client_id": 1,
    "file": file_string
}
headers = {
    "token": "AuthTokenGoesHere",
    "content-type": "application/json",
}
request = requests.post('https://api.website.com/api/files/', json=payload, headers=headers)
print(request.json())
</code></pre>

<p>models.py</p>

<pre><code>def upload_location(instance, filename):
    return '%s/documents/%s' % (instance.user.username, filename)

class Document(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL)
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    file = models.FileField(upload_to=upload_location)

    def __str__(self):
        return self.filename()

    def filename(self):
        return os.path.basename(self.file.name)
</code></pre>

<p>So to reiterate, when a user uploads a file, instead of storing the file somewhere on the web server, I want to base64 encode the file so I can send the file as a JSON payload. Any ideas on what would be the best way to approach this? </p>