read image upload response - nativescript

Im using this code for uploading images:
https://github.com/NativeScript/sample-ImageUpload
When i upload an image i got success notification.
I'm trying to read response from server and also checked task's complete event:
task.on("complete", logEvent);
function logEvent(e) {
console.log(JSON.stringify(e));
}
and this is the output:
{"eventName":"complete","object":{"_observers":{"complete":[{}],"propertyChange":[{}]},"_session":{"_id":"image-upload"},"_id":"image-upload{1}","_description":"{ 'uploading': Test0.png }","_upload":3807297,"_totalUpload":3807297,"_status":"complete"},"response":{}}
as you can see response is null. So how can i read the response from server?

the data told you why is null ?
it is not finish to upload is only in session.
look here at the send image function , what are youy need to do.

Related

How to send Image to to Rest API using json

I am getting an image from a form and sending it to rest api using requests modules which I want to save later in the models. but the issue is I am getting the image from form but when It reached the API it is autmatically a string and I dont know how to get that image in the API.
image.py (here I am getting the image in the image variable
image_file= request.FILES.get('image')
if request.method == "POST":
headers={"Content-Type": 'multipart/form-data','Authorization': 'Token {}'.format(token) }
url = f"http://127.0.0.1:8000/api/pay-committee/"
data = {
"mem_id": 4,
"payment_proof" :image_file
}
response = post_url(url,request,data)
here I am getting the image but when I check the type it is not the image instead it is only string name
def post(request):
payment_proof = (request.data['payment_proof'])

Why Laravel API request sent from Vue gets canceled

I'm trying to send formData from Vue using Axios to Laravel (v6) API on Laravel Homestead containing some data and an excel file to read and validate data in the backend. If the sheet contains records than 800 for example everything works file but when I increased it to 850 or 1000 the request gets cancelled I don't know why.
Successful request
Cancelled request
As you see it doesn't reach the actual request like the successful request it just gets cancelled at the beginning.
But the weird thing is that the data got validated and inserted into the DB already but the response gets converted to cancelled and the actual success response doesn't get returned from the API
Is this error related to server configurations or needs code fix?
Vue code
submitImportedUsers(){
let formData = this.gatherFormData();
this.importUsers(formData);
},
gatherFormData() {
//create formData to send normal dta with files
let formdata = new FormData();
formdata.append("users", this.form.usersFile);
formdata.append("images", this.form.imagesFile);
const json = JSON.stringify({
unique_fields: this.form.uniqueFields,
update_duplicates: this.form.duplicateUsers,
entity_id: this.entityId,
user_id: this.userId,
});
formdata.append("data", json);
return formdata;
Laravel
$usersImportService->moveFile($request->file('users'));
public function moveFile($file) {
if(is_null($this->folderName) || !isset($this->folderName)){
$this->generateUuid();
}
$ext = $this->getRequestFileExt($file);
$usersFileName = $this->folderName.'.'.$ext;
$this->fileName = $usersFileName;
$path = storage_path().'/uploads';
\File::isDirectory($path) or \File::makeDirectory($path, 0777, true, true);
move_uploaded_file($file->getRealPath(), $this->storePath.$usersFileName);
}
Then start reading it using Laravel Excel and insert the data into the database
I found the issue which the front end developer did in axios instance that might help anyone facing this issue
axiosInstance.defaults.timeout = 10000;
It could be anything like that used to set the timeout of axios it's set to 10 seconds here and the request needs more time so setting this to a higher value solved the issue

POST request response being sent in weird format

I intend to send my server response in the following format
Api Doc
I did the following
headersR.add("response_code", "OK");
headersR.add("cmd_code", "SET_FK_NAME");
headersR.add("trans_id", Long.toString(System.currentTimeMillis()/1000000));
JSONPObject map1 = new JSONPObject("fk_name", "jj");
return new ResponseEntity<>(map1, headersR, HttpStatus.OK);
I was getting a negative response from the other side so I checked Wireshark(Had a hard time logging my response body). And I got this in Wireshark.
Wirehark Screenshot
The response body is Definitely not JSON.
How can I fix this?
The response body fk_name("jj") is not JSON, it's JSONP -- Browser would take the function name fk_name and try to execute it with "jj" as parameter.
The root cause is you are using JSONPObject, whose constructor accepts 2 parameters: a function name, and the data value. Not the expected JSON key and value.
To fix this issue and return {"fk_name":"jj"}, remove the JSONPObject stuff and use code as follow:
return new ResponseEntity<>("{\"fk_name\":\"jj\"}", headersR, HttpStatus.OK);

Parse.File Invalid file url

Does anyone know how to set a simple js Object to Parse.Object's field with type 'file' and save it successfully?
I have a model like
{...
picture: 'file',
...
}
I upload a file via server side and get an {name,url} object.
Send it to front-end as JSON.
After that I'm trying to use this JSON as picture
{...
picture: {name,url},
...
}
via POST request to the server(model.save(params)) but have just
{ code: 111,
message: 'Invalid file url: "http://s3.amazonaws.com/files.parsetfss.com/4d46bc83-d162-4d44-8462-d695f008f787/tfss-8c096482-2b88-4509-a99c-4c99ae57d51d-cat.jpg"' }
There is an approach without duplicate pictures like Cloud Code: Creating a Parse.File from URL?
Artyom24 was right.
I've removed s3.amazonaws.com/ and now everything is ok.

How to handle application errors for json api calls using CakePHP?

I am using CakePHP 2.4.
I want my frontend make api calls to my CakePHP backend using ajax.
Suppose this is to change passwords.
Change password action can throw the following application errors:
old password wrong
new password and confirm new passwords do not match
In my frontend, I have a success callback handler and a error callback handler.
The error callback handler handles all the non 200 request calls such as when I throw NotFoundException or UnAuthorizedAccessException in my action.
The success callback handler handles all the 200 request calls including of course, the above 2 scenarios.
My questions are:
Should I continue to do it this way? Meaning to say, inside all success callback handler, I need to watch out for application success and application error scenarios.
Should I send application errors back with actual HTTP error codes?
if I should do 2, how do I implement this in CakePHP?
Thank you.
Don't use http error codes for system errors like:
old password wrong
new password and confirm new passwords do not match
etc etc...
Now using success handler you can show messages and code flow as:
Create Ajax post or get to submit the form, I am showing you post example
var passwordValue = $('#password').val();
$.post( "/updatePassword", { passwordText: passwordValue })
.done(function(response) {
if(response.status === 'Success'){
// Success msg
// whatever
}else{
// Error msg
// whatever
}
});
json response would like:
{
"status": "Failed/Success",
"message": "old password wrong."
}
Create one function in controller
public function updatePassword() {
$myModel = $this->MyModel->find('first' // YOUR CODE LOGIC);
if($this->request->is('ajax') {
$this->layout=null;
// What else?
echo json_encode($myModel);
exit;
// What else?
}
}
Do something like this, hope it will solve your query!

Resources