Accessing an uploaded image


I am working with the single file uploader and have gotten access to the file with and understand that part but I am confused on how to access it as an image type and not a File type. Essentially, I am trying to make it so that a user is able to upload an image and the code is going to take this image and apply a machine learning model to the image but I have not been able to get the file into a usable format for the model. Let me know if this question does not make sense and I can try and rephrase or include code examples


Code examples are always a great idea, as they can quickly illuminate what you are trying to do.

For now, my hunch is you are trying to get the user to upload an image, and then you want to β€œgive” that image to another piece of code to interpret. As we describe in the docs you can upload a file and access it’s content doing something like:

from viktor.parametrization import ViktorParametrization, FileField, MultiFileField

class Parametrization(ViktorParametrization):
    cpt_file = FileField('CPT file')

class Controller(ViktorController):
    def get_cpt_file(self, params, **kwargs):
        cpt_file = params.cpt_file.file
        return cpt_file

According to the docs this returns a VIKTOR File object. Perhaps your model can take just the bytes, which you could get through file.getvalue_binary(). Or you perhaps need to give it to a file-like object. In Python using BytesIO is a very common thing to do in these situations. To create a BytesIO object and fill it you can do:

from io import BytesIO


class Controller(ViktorController):
    def get_bytesio_from_file(self, params, **kwargs):
        cpt_file = params.cpt_file.file
        bio_obj = BytesIO(cpt_file.getvalue_binary())
        return bio_obj

This worked perfectly. Thank you very much

1 Like