im working in uploading image in mysql database with android studio
my function in laravel
public function ajouter(Request $req){
try {
$produit= new Produit;
$produit->name= $req->name;
if($req->file('name')){
$path = Storage::disk('produits')->putFile('',$req->file('name'));
$produit->name = $path;
}
$produit->description= $req->description;
$produit->poids= $req->poids;
$produit->category_id= $req->category_id;
$produit->user_id= $req->user_id;
$produit->volume= $req->volume;
$produit->save();
return response()->json([
'status' => 'success',
'data' => $produit
]);
} catch (Exception $e) {
return response()->json([
'status' => 'error',
'data' => 'error'
]);
}
i have tested it with postman and it works.
i have created an interface in android
public interface AjouterProduit {
String AJOPROD = "http://IP/AnnocesPFE/public/api/";
#Multipart
#POST("produits")
Call<String> getAjoutProd(
#Part MultipartBody.Part name,
#Part("description") String description,
#Part("poids") String poids,
#Part("volume") String volume,
#Part("category_id") int category_id,
#Part("user_id") int user_id
);
}
im blocked how to send all the informations to the database any help ?
Related
I'm learning Dart (from a Java developer history), I'm working in a simple message application on Flutter.
The unique problem that I have is when I try to include a new Message in the chat's history. I am updating de array of messages in the app (Dart) and sending the entire object (Complex object with the messages array inside) to update via FirebaseFirestore to Firebase.
But I'm getting this error
I/flutter (16604): Invalid argument: Instance of 'Message'
This is my code
Adding a new message to the actual array
Message newMessage = Message('Test text',DateTime.now(), 'From me', 'For U' conversation.id);
messagesQueue.add(newMessage);//add the message to the actual array
conversation.messages = messagesQueue;
updateConversation(conversation);
Conversation object makes this transformation to send to Firebase
class Conversation {
String id;
String owner;
String destinationName;
String destination;
List<Message> messages;
String lastMessageDate;
....
//Transformacion para Firebase
Map<String, dynamic> toMap(Conversation conversation) {
return <String, dynamic>{
//'id': conversation.id,
'owner': conversation.owner,
'destinationName': conversation.destinationName,
'destination': conversation.destination,
//'messages': conversation.messages,
'messages' : List<dynamic>.from(conversation.messages.map((x) => x.toMap())),
'lastMessageDate': conversation.lastMessageDate
};
if I delete this line 'messages' : List<dynamic>.from(conversation.messages.map((x) => x.toMap())), the update works fine (no update messages obvious)
Message.dart code
class Message {
String text;
DateTime sendedTime;
String from;
String to;
String conversationId;
Message(
this.text,
this.sendedTime,
this.from,
this.to,
this.conversationId,
);
Map<String, dynamic> toMap() => {
"text": text,
"from": from,
"to": to,
"sendedTime": sendedTime.toIso8601String(),
"conversationId": conversationId,
};
}
The update method
Future<bool> updateConversation(Conversation conversation) async {
try {
await db.collection('conversations').doc(conversation.id).update(toMap(conversation));
return true;
} catch (e) {
print(e);
return false;
}
}
What is wrong with the List messages transformation?
UPDATE
I've added this line (var jsonMessages = conversation.messages.map((e) => e.toMap()).toList();) and the update works, but now I'm getting this error
_Error type 'InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Message'
Future<bool> updateConversation(String id, Conversation conversation) async {
try {
var jsonMessages = conversation.messages.map((e) => e.toMap()).toList();
//await db.collection('conversations').doc(id).update(toMap(conversation));
await db
.collection('conversations')
.doc(id)
.update({'messages': jsonMessages});
return true;
} catch (e) {
print(e);
return false;
}
}
Solved
Transformation from Firestore
Conversation.fromFirestore(DocumentSnapshot doc)
: id = doc.id,
owner = doc.get("owner"),
destinationName = doc.get("destinationName"),
destination = doc.get("destination"),
messages = List<Message>.from(
doc.get("messages").map((e) => Message.fromMap(e))),// this is the trick!
lastMessageDate = doc.get("lastMessageDate");
I'm currently working with React native mobile application, on this process I use SQLite to store data locally within the phone the problem is I have assigned a variable getToken which need to be filled by the token I stored in SQLite DB. below is the method i tried and it always returns the default value.
function getTest() {
let getToken = 'ABC';
db.transaction(tx => {
tx.executeSql('SELECT * FROM Login', [], (tx, result) => {
getToken = result.rows.item(0).access_token;
});
});
return getToken;
}
The problem occurs because of transaction and executeSQL are async methods. Try using await or resolve a promise inside executeSQL callback. i solved this issue as follows
async function returnToken() {
return new Promise((resolve, reject) => {
db.transaction(tx => {
tx.executeSql('SELECT * FROM Login', [], (tx, result) => {
let accessToken = result.rows.item(0).access_token;
resolve(accessToken);
});
});
});
}
async function (config){
let token = await returnToken();
console.log('token', token);
}
I'm recreating a project that was originally designed for Native Android to use React Native. There is an endpoint that is responsible to send a image using Form Data. I tried to convert the OkHttp3's Form Data to Axios's Form Data and I'm getting an error from backend saying that the request fields doesn't match.
My Code so far:
- Native Android(original app):
public RequestResponse<Boolean> functionApi(#NonNull String id, String imageExtension, #NonNull byte[] imageData, #NonNull String anotherData) throws ServerErrorException, IOException, AuthenticationException {
String path = "route/" + id;
Pair<String, String> contentTypeHeader = new Pair<>("Content-Type", "multipart/form-data");
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("anotherData", anotherData)
.addFormDataPart("imageData", id + "." + imageExtension, RequestBody.create(MediaType.parse("image/png"), imageData))
.build();
Response response = MyHttpClient.execute(path, "POST", requestBody, contentTypeHeader);
String body = response.body().string();
RequestResponse<Boolean> r = responseBodyToObject(body, RequestResponse.class);
r.setBody(r.getStatus() != RequestResponse.ERROR);
return r;
}
React Native(new app) version:
export const functionApi = async(id,imageExtension,imageData,anotherData)=>{
try{
let formData = new FormData()
formData.append('anotherData',anotherData)
formData.append('imageData',`data:image/${imageExtension};base64,${imageData}`,`${id}.${imageExtension}`)
//imageData here i tried to use a base64's string
let res = await axios({
url:`${URL_SERVER}/route/${id}`,
method:'POST',
headers:{
'Content-Type':"multipart/form-data"
},
data:formData
})
return res['data']
}catch(err){
return getErrorMessage(err)
}
}
I got a solution that finally worked for me:
export const functionApi = async(id,imageExtension,imageData,anotherData)=>{
try{
let formData = new FormData()
formData.append('anotherData',anotherData)
formData.append('imageData',{
uri: imageData['uri'],
type: 'image/jpg',
name: `${id}.${imageExtension}`,
})
let res = await axios({
url:`${URL_SERVER}/route/${id}`,
method:'POST',
headers:{
'Content-Type':'multipart/form-data'
},
data:formData
})
return res['data']
}catch(err){
return getErrorMessage(err)
}
}
I have a Retrofit API call to my Laravel server:
#POST("/dualsimlog")
Call<ResponseBody> submitLogs(#Body List<ServerLog> serverLogs);
Here is the Retrofit implementation:
List<ServerLog> unsubmitted = logHelper.getLogInfo();
retrofit2.Call<ResponseBody> call = logServices.submitLogs(unsubmitted);
call.enqueue(new retrofit2.Callback<ResponseBody>() {
#Override
public void onResponse(retrofit2.Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
L.m(response.message());
}
#Override
public void onFailure(retrofit2.Call<ResponseBody> call, Throwable t) {
L.m("Submission failed.");
}
});
My Laravel store API for a single object is:
public function store(Request $request)
{
// validating object variables
$rules = [
'device_id' => 'required|string',
'type' => 'required|string',
'sim1_cost' => 'required|numeric|min:0',
'sim2_cost' => 'required|numeric|min:0',
'cost_saved' => 'required|numeric|min:0',
'call_duration' => 'required|numeric|min:0',
'created_at' => 'required|date',
];
$data = $request->all();
$validator = Validator::make($data, $rules);
if ($validator->fails()) {
return $this->errorResponse("Validation error.",400 );
}
$product = DualSimLog::create($data);
return $this->showMessage("Successful.");
}
How to modify the API to validate and insert the list of ServerLog objects?
Moreover how to debug Laravel projects in PhpStorm when using Android for sending the API request?
you need use #FormUrlEncoded in retrofit, see this link
My environment is Android and i use Xamarin for do my project.
I have a problem with my connection to server, for that i use Json my error is :
`Newtonsoft.Json.JsonReaderException: Error reading JObject from JsonReader. Current JsonReader item is not an object: String. Path '', line 1, position 2. at Newtonsoft.Json.Linq.JObject.Load`
so my code app side is :
public async Task Login (string user_email, string user_password)
{
var content = new Dictionary<string, string> { {
"user_email",
user_email
},
{
"user_password",
user_password
}
};
String str = await ProcessPOST ("/api/login", content);
JObject data = JObject.Parse (str);
if (data ["success"] != null)
return (string)data ["success"];
throw new Exception ((string)data ["error"]);
}
and server side is :
So login
public function login() {
if ($this->method == "POST") {
if ($this->_data("user_email") && $this->_data("user_password")) {
$u_dao = new UserDAO();
$users = $u_dao->executeSelect("WHERE user_email = :user_email", array("user_email" => $this->_data("user_email")));
if (!isset($users[0]))
return $this->_response(array("error" => "User not found"), 403);
$user = $users[0];
if ($user && crypt($this->_data("user_password"), $user->user_password) == $user->user_password) {
$token = bin2hex(openssl_random_pseudo_bytes(16));
$user->user_token = $token;
$u_dao->update($user);
return $this->_response(array("success" => $token));
}
return $this->_response(array("error" => "Bad login"), 403);
}
return $this->_response(array("error" => "Missing data"), 500);
}
return $this->_response(array("error" => "Wrong method"), 405);
}
and code of _response
protected function _response($data, $status = 200) {
header("HTTP/1.1 " . $status . " " . $this->_requestStatus($status));
return json_encode($data);
}
and now of _requestStatus
private function _requestStatus($code) {
$status = array(
200 => 'OK',
403 => 'Forbidden',
404 => 'Not Found',
405 => 'Method Not Allowed',
500 => 'Internal Server Error',
);
return ($status[$code]) ? $status[$code] : $status[500];
}
and when i try to connect my web service is online , but i forget to said when i have error like "Missing Data" i haven't error of JObject but when i have success i have error.
so i show to all two str one of error:
"{\"error\":\"Missing data\"}"
and one of succes:
"''{\"success\":\"db035db78a9f1e64d71c83bcbb45ffa5\"}"
i want to said thanks to all people which help me . And i'm sorry for my bad english but i'm french .
i hope to be clear but if u have question u can ask them.
I don't see any necessary use for Json.net here. I would simplify and just check if the response contains "success" or "error".