Django REST API configurations receiving image from android - android

Hi I am new to Django and I am currently using it to create a web service. I am connecting android to django and would like to upload and image from android to django imagefield. I am using serializer to save the data in json. this code works on normal web, however, I am not sure what image file format to send over to the server and how to configure the server's file handling
This is what my views.py looks like :
`def post(self, request):
serializer = PhotoSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)`

Hi you should try to create a serializers class for save the image from that way:
class ModelNameSaveSerializers(serializers.ModelSerializer):
image_field = serializers.ImageField()
class Meta:
model = ModelName
fields = ('id'.. antoher_fields, 'image_field')

Related

Android studio Display image from Laravel API

I am using Retrofit API to access my Laravel site data. I am not able to display images in my android app.
Here is my Laravel code to save images in my Laravel site.
$path = 'images/no-thumbnail.jpeg';
if($request->has('thumbnail')){
$extension = ".".$request->thumbnail->getClientOriginalExtension();
$name = basename($request->thumbnail->getClientOriginalName(), $extension).time();
$name = $name.$extension;
$path = $request->thumbnail->storeAs('images', $name, 'public');
}
Here is the API response for the Products tabel.
[{"id":1,"user_id":"1","title":"White T shirt","description":"White T shirt small size","categorie":"1","price":"50","discount_price":"0","thumbnail":"images\/81vzc0ciKwL._AC_UX679_1619280040.jpg","slug":"white-t-shirt","options":null,"featured":"0","status":"0","created_at":"2021-04-24T16:00:40.000000Z","updated_at":"2021-04-24T16:00:40.000000Z","deleted_at":null}]
The response of the image is this "thumbnail":"images/81vzc0ciKwL._AC_UX679_1619280040.jpg"
For my android app, I am using Picasso here is the code.
Picasso.get().load(shopesModel.getThumbnail()).into(holder.shopImg);
But still, I am not getting images in my android app. I am getting other fields of the product table.
Here is the screenshot of the app
Where should I change my code. Laraval or change my app code so that I can get images from Laravel.
Since your json response doesn't have qualified url in thumbnail
"thumbnail":"images\/81vzc0ciKwL._AC_UX679_1619280040.jpg"
There two ways you can fix
1.best solution is to send full url image path from server side
2.hardcoding base url in your android and append to Picasso
"thumbnail":"https://urdomain/storage/images/81vzc0ciKwL._AC_UX679_1619280040.jpg"
or
String baseUrl="https://urdomain/storage/";
Picasso.get().load(baseUrl+shopesModel.getThumbnail()).into(holder.shopImg);

Put File as Binary with Ktor HttpClient in Kotlin Multiplatform Project

I have a multiplatform project in which api code is shared between iOS and Android.
There is "put" api to upload local audio file as Binary.
Ive created httpclient as follows
val client = HttpClient {
defaultRequest {
url {
protocol = ServiceConfiguration.protocol
host = ServiceConfiguration.baseUrl
port = ServiceConfiguration.port
}
contentType(ContentType.Application.Json)
}
install(JsonFeature) {
val json = kotlinx.serialization.json.Json {
ignoreUnknownKeys = true
isLenient = true
}
serializer = KotlinxSerializer(json)
}
}
To put the object into api, I am doing as follows
val response = ServiceRequest.client.put<String>(
body = File(path).readBytes()
)
It works fine and uploads the byte array to backend. But instead of byte array I want to upload the file as plain binary.
To make it more clear, In Postman mac app we can upload file as binary . I need to do similar thing.
When I checked in Ktor, it shows only multi-part form data can be submitted as binary. But In my case it is Put request.
Please help.
Looks like there is no straightforward way to put file as binary with Ktor.
I had to go for platform Dependent approaches like OkHttpClient for Android and URLSession for iOS.

Django REST Framework: sending an image from android

I'm trying to send an image through my Android application to Django, where it will make the analysis of that image (with python code). I'm sending the image in Base64, but when I receive it, the format gets all messed up. How can I send the image correctly, and is this the right format?
Have you tried using this?
link
combined with a code like that:
class UploadedImageSerializer(serializers.ModelSerializer):
"""
Serializer for the UPloadedImage Model
Provides the pk, image, thumbnail, title and description
"""
class Meta:
model = UploadedImage
fields = ('pk', 'image', 'thumbnail', 'title', 'description', )
read_only_fields = ('thumbnail',)

Upload image from android to django rest framework using google app engine + google cloud sql + cloudinary.

i have a regist form with their fields, but I can not upload an image from android to cloudinary, and save the url in google cloud sql.
my android code:
String senderPart = MyApplication.getInstance().getPrefManager().getUser().getUrl();
entity.addPart("perfil", new FileBody(sourceFile));
entity.addPart("user", new StringBody(senderPart));
senderPart is the url from my user.
sourceFile is the path of my image profile.
django rest framework code model:
class AgregarFotoPerfil(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
perfil = CloudinaryField('perfil')
view.py:
class PerfilViewSet(viewsets.ModelViewSet):
queryset = AgregarFotoPerfil.objects.all()
serializer_class = ImgPerfilSerializer
serializer.py:
class ImgPerfilSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = AgregarFotoPerfil
fields = ('url', 'perfil', 'user')
google app engine error:
TypeError: Got a `TypeError` when calling `AgregarFotoPerfil.objects.create()`. This may be because you have a writable field on the serializer class that is not a valid argument to `AgregarFotoPerfil.objects.create()`. You may need to make the field read-only, or override the ImgPerfilSerializer.create() method to handle this correctly.
Original exception text was: has type , but expected one of: str, unicode.

How to receive images from Android and iOS to Rails 3.2.8 using multipart and Carrierwave?

How should my controller action look like when receiving image from an Android or iPhone?
My image model is the following:
class Image < ActiveRecord::Base
attr_accessible :user_id, :file_path
belongs_to :user
mount_uploader :file_path, FileUploader
end
The current controller:
class ImagesController < ApplicationController
protect_from_forgery :except => [:upload]
def upload
user = User.find(params[:user_id])
# I have no idea what else I have to do...
end
end
I'm in doubt how Carrierwave magically save the files to the server and what should I do in the controller to receive that Post.
file_path is now a field in your model. This means when you pass that field into your controller when creating a new model, it will automatically pick that up and save it.
Your multipart file data should be send as params[:image][:file_path] when creating a new Model, assuming the create method in your controller is being passed params[:image].

Categories

Resources