In the ViewModel I get the image in an array of bytes and add it to a MultipartDataContent.
byte[] imageArray = null;
ByteArrayContent imageStream= null;
if (this.file != null)
{
imageArray = FilesHelper.ReadFully(this.file.GetStream());
imageStream = new ByteArrayContent(imageArray);
imageStream.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = Guid.NewGuid() + ".Png"
};
}
this.FechaInicio = this.DateSelected.Year + "-" + this.DateSelected.Month + "-" + this.DateSelected.Day;
this.FechaFin = this.DateSelectedFin.Year + "-" + this.DateSelectedFin.Month + "-" + this.DateSelectedFin.Day;
this.Fecha = DateTime.Today.Year + "-" + DateTime.Today.Month + "-" + DateTime.Today.Day;
Comunicado comunicado = new Comunicado { Fecha_inicio=this.FechaInicio, Fecha_fin= this.FechaFin,
Contenido = this.Contenido,Tipo= this.TipoSelectedIndex, Asunto= this.Asunto, Fecha_creacion= fecha, Materia=selectedMateria.Id,User_id=1,Path= imageArray };
this.IdColegio = 1;
MainViewModel.GetInstance().ComunicadoCursos = new ComunicadoCursosViewModel(comunicado,this.IdColegio);
Application.Current.MainPage = new ComunicadoCursosPage();
return;
Send method in which I send the image within the class Communicated in the Path attribute
private async void Enviar()
{
var connection = await this.apiService.CheckConnection();
if (!connection.IsSuccess)
{
await Application.Current.MainPage.DisplayAlert(
"Error",
connection.Message,
"Accept");
await Application.Current.MainPage.Navigation.PopAsync();
return;
}
Comunicados.Prioridad = PrioridadSelectedIndex + 1;
var response = await this.apiService.Post<Comunicado>(
MainViewModel.GetInstance().BaseUrl,
"/comunicado",
"/api/v1/listar",
Comunicados);
if (!response.IsSuccess)
{
await Application.Current.MainPage.DisplayAlert(
"Error",
response.Message,
"Accept"
);
return;
}
await Application.Current.MainPage.DisplayAlert(
"Mensaje",
"Registrado correctamente",
"Accept");
//MainViewModel.GetInstance().AgendaMedico = new AgendaMedicoViewModel(this.idMedico);
//Application.Current.MainPage = new NavigationPage(new AgendaMedicoPage());
return;
}
The file Comunicado.cs
public class Comunicado
{
[JsonProperty(PropertyName = "id")]
public int Id { get; set; }
[JsonProperty(PropertyName = "prioridad")]
public int Prioridad { get; set; }
[JsonProperty(PropertyName = "fecha_inicio")]
public string Fecha_inicio { get; set; }
[JsonProperty(PropertyName = "fecha_fin")]
public string Fecha_fin { get; set; }
[JsonProperty(PropertyName = "contenido")]
public string Contenido { get; set; }
[JsonProperty(PropertyName = "path")]
public byte[] Path { get; set; }
[JsonProperty(PropertyName = "tipo")]
public int Tipo { get; set; }
[JsonProperty(PropertyName = "asunto")]
public string Asunto { get; set; }
[JsonProperty(PropertyName = "fecha_creacion")]
public string Fecha_creacion { get; set; }
[JsonProperty(PropertyName = "user_id")]
public int User_id { get; set; }
[JsonProperty(PropertyName = "materia")]
public int Materia { get; set; }
}
Models.py File
class Comunicado(models.Model):
PRIORIDAD_CHOICES = (
(1, ("Urgente")),
(2, ("Medio")),
(3, ("Normal"))
)
TIPO_CHOICES = (
(1, ("Comunicado")),
(2, ("Evento"))
)
prioridad = models.IntegerField(choices=PRIORIDAD_CHOICES, default=1)
fecha_inicio = models.DateField()
fecha_fin = models.DateField()
contenido = models.TextField()
path = models.ImageField(upload_to=comunicado_directory_path, blank=True, null=True,default='comunicado/cancel.png',max_length=5000)
tipo = models.IntegerField(choices=TIPO_CHOICES, default=1)
asunto = models.CharField(max_length=100)
fecha_creacion = models.DateField(default= date.today)
user_id = models.ForeignKey(User , null=True, blank=True, on_delete=models.CASCADE)
materia = models.ForeignKey(Materia , null=True, blank=True, on_delete=models.CASCADE)
curso = models.ManyToManyField(Curso, through='CursoComunicado')
def __str__(self):
return self.asunto
View.py file
class ListComunicado(APIView):
def get(self, request):
comunicado = Comunicado.objects.all()
comunicado_json = ComunicadoSerializer(comunicado, many=True)
return Response(comunicado_json.data)
def post(self, request):
try:
file = request.data['path']
fecha_inicio = request.data['fecha_inicio']
fecha_fin = request.data['fecha_fin']
contenido = request.data['contenido']
tipo = request.data['tipo']
asunto = request.data['asunto']
fecha_creacion = request.data['fecha_creacion']
materia = request.data['materia']
user_id = request.data['user_id']
prioridad = request.data['prioridad']
except KeyError:
print("Error")
rawbytes = bytes(file, 'utf-8')
print(rawbytes)
image_bytes = Image.open(io.BytesIO(rawbytes))
pil_image = Image.open(image_bytes)
pil_image.verify()
user = User.objects.get(pk = user_id)
materia = Materia.objects.get(pk = materia)
comunicado = Comunicado.objects.create(path = pil_image, prioridad = prioridad, fecha_inicio = fecha_inicio, fecha_fin = fecha_fin,
contenido = contenido, tipo = tipo, asunto = asunto, fecha_creacion = fecha_creacion,
user_id = user, materia = materia)
I get the array of bytes in the file variable
Serializers.py Files
class ComunicadoSerializer(serializers.ModelSerializer):
path = serializers.ImageField(max_length=None, use_url=True)
class Meta:
model = Comunicado
fields = ('id','prioridad','fecha_inicio','fecha_fin','contenido','path', 'tipo', 'asunto', 'fecha_creacion', 'user_id', 'materia')
I am trying to convert the array of bytes into an image. With the python PIL library but I get the following error.
Traceback (most recent call last): File "D: \ DjangoProjects \ venv \ lib \ site-packages \ django \ core \ handlers \ exception.py", line 35, in inner response = get_response (request) File "D: \ DjangoProjects \ venv \ lib \ site-packages \ django \ core \ handlers \ base.py", line 128, in _get_response response = self.process_exception_by_middleware (e, request) File "D: \ DjangoProjects \ venv \ lib \ site-packages \ django \ core \ handlers \ base.py", line 126, in _get_response response = wrapped_callback (request, * callback_args, ** callback_kwargs) File "D: \ DjangoProjects \ venv \ lib \ site-packages \ django \ views \ decorators \ csrf.py", line 54, in wrapped_view return view_func (* args, ** kwargs) File "D: \ DjangoProjects \ venv \ lib \ site-packages \ django \ views \ generic \ base.py", line 69, in view return self.dispatch (request, * args, ** kwargs) File "D: \ DjangoProjects \ venv \ lib \ site-packages \ rest_framework \ views.py", line 483, in dispatch response = self.handle_exception (exc) File "D: \ DjangoProjects \ venv \ lib \ site-packages \ rest_framework \ views.py", line 443, in handle_exception self.raise_uncaught_exception (exc) File "D: \ DjangoProjects \ venv \ lib \ site-packages \ rest_framework \ views.py", line 480, in dispatch response = handler (request, * args, ** kwargs) File "D: \ DjangoProjects \ venv \ webweb \ apps \ statement \ views.py", line 44, in post image_bytes = Image.open (io.BytesIO (rawbytes)) File "D: \ DjangoProjects \ venv \ lib \ site-packages \ PIL \ Image.py", line 2622, in open % (filename if filename else fp)) OSError: can not identify image file