1

i have JSON request like this:

object: { "fields":{ "src" : "http://dss.com/a.jpg", "data" : " //file is here" } }

i have the model like this:

class FileMy(models.Model): f = models.FileField(upload_to='file_path/',)

How to save the file ?

  • 1
    i don't think that is the proper way, you need a form on the client side that posts the file to the django view which can then save the file in the file system. you probably don't want to store a blob image in your database but just a reference to where the file can be found on your file system. This link may help in regards to an upload form posting an image to a django view via ajax. https://waaave.com/tutorial/django/how-to-quickly-upload-files-in-ajax-with-django-in-5-steps/ – Chris Hawkes Feb 03 '15 at 16:17
  • thanks, i split JSON and file data – user3673451 Feb 03 '15 at 20:02

3 Answers3

0

You may use urllib to read the file and then you can add it to your model.

Take a look at this post: Django: add image in an ImageField from image url

Community
  • 1
  • 1
danieltellez
  • 206
  • 1
  • 11
0

You may be able to wrap the data in a ContentFile which inherits from File and then save the file to the model directly.

from __future__ import unicode_literals
from django.core.files.base import ContentFile

from .models import FileMy

f1 = ContentFile("esta sentencia está en español")
f2 = ContentFile(b"these are bytes")
m1 = FileMy()
m2 = FileMy()
m1.f.save("filename", f1, save=True)
m2.f.save("filename", f2, save=True)
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
0

First of all, encode the raw data in the json request body.

from tempfile import NamedTemporaryFile
from django.core.files import File

def save_file_to_field(field, file_name, raw_content):
    # field: reference to the model object instance field
    img_temp = NamedTemporaryFile(delete=True)
    img_temp.write(raw_content)
    field.save(
        file_name,
        File(img_temp)
    )
    img_temp.flush()

What does this do:

  • creates a temporary file on your system that holds the data
  • uses the file field save method to trigger the usual file handling
  • deletes the temporary file
vladimir.gorea
  • 641
  • 1
  • 8
  • 27