Dimag Kharab
Dimag Kharab

Reputation: 4519

Corrupted Image upload from Django

This is my code for uploading image that I have defined in a class based view,

def _handle_uploaded_file(self, request):

        folder = settings.MEDIA_ROOT
        uploaded_filename = request.FILES['img_fl'].name

        BASE_PATH ='/home/admin1/Desktop/virtualenv-12.1.1/mapfied'
        # create the folder if it doesn't exist.
        try:
            os.mkdir(os.path.join(BASE_PATH, folder))
        except Exception as e:
            pass

        # save the uploaded file inside that folder.
        full_filename = os.path.join(BASE_PATH, folder, uploaded_filename)

        fd = open(full_filename, 'wb')

        file_content = ContentFile( request.FILES['img_fl'].read() )

        try:
            for chunk in file_content.chunks():
                fout.write(chunk)
            fout.close()
                html = "<html><body>SAVED</body></html>"
                print(html)
        except Exception as e:
            print(e)

The image file is getting saved to correct location with name, but it is corrupted.I am unable to find the exact reason for this , Am I doing something wrong here?

Upvotes: 0

Views: 995

Answers (2)

Cheng
Cheng

Reputation: 17904

This is what I had from a previous project for writing upload files to disk:

def view_handling_function(request):
    for key, value in request.FILES.iteritems():
        full_path = ...
        save_uploadfile_to_disk(full_path, value)

def save_uploadfile_to_disk(full_path, file):
    with open(full_path, 'w+') as destination:
        for chunk in file.chunks():
            destination.write(chunk)

Upvotes: 2

Dwight Gunning
Dwight Gunning

Reputation: 2525

I think since you're looking to write a binary upload you need to open the file with writable binary mode which is actually wb+.

You could also tidy up a bit by using the 'with' keyword; see Django example here.

Sidenote: if you're persisting the file as a FileField (or a derived class) you could just provide the 'upload_to' function that returns the full path and file name for where you'd like to store the file. That'll let the framework take care of the file io for you.

Upvotes: 1

Related Questions