0

I am working on a django project where i try to upload a file via http post request.

my upload script is :

url=r'http://MYSITEURL:8000/upload'
files={'file':open('1.png','rb')}
r=requests.post(url,files=files)

my receiving side is in my django site , in views.py:

def upload_image(request):
from py_utils import open_py_shell;open_py_shell.open_py_shell()

when i do request.FILES i can see all the post details, what i want to know is how to save it in the server side once i got the post request

1
  • Looks like you've solved 'script to upload file' and you're trying to solve 'handle uploaded file'. You should probably change your title. Commented Feb 23, 2015 at 9:41

2 Answers 2

1

What you have in request.FILES is InMemoryUploadedFile. You just need to save it somewhere in file system.

This is example method taken from Django docs:

def handle_uploaded_file(f):
    with open('some/file/name.txt', 'wb+') as destination:
        for chunk in f.chunks():
            destination.write(chunk)
Sign up to request clarification or add additional context in comments.

1 Comment

it is not clear why + file mode is used (the destination is write-only) -- is it some permission-related hack? It is also not clear why shutil.copyfileobj(f, destination) is not used.
0

I think you can work with models well. It will be the right way for Django. Here is an example, models.py file:

from django.db import models
from django.conf import settings

import os
import hashlib


def instanced_file(instance, filename):
    splitted_name = filename.split('.')
    extension = splitted_name[-1]
    return os.path.join('files', hashlib.md5(str(instance.id).encode('UTF-8')).hexdigest() + '.' + extension)

class File(models.Model):
    name = models.FileField('File', upload_to = instanced_file)

    def get_file_url(self):
        return '%s%s' % (settings.MEDIA_URL, self.name)

    def __str__(self):
        return self.name

    def __unicode__(self):
        return self.name

After the creating models create forms and go on.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.