How to upload image in nativescript - nativescript

I'm trying to upload an image via nativescript-background-http plugin.
this my code:
var session = bghttp.session("image-upload");
var request = {
url: 'http://localhost:4200/',
method: "POST",
headers: {
"Content-Type": "application/octet-stream",
"File-Name": imageFile.name
},
description: "{ 'uploading': " + imageFile.name + " }"
};
var task = this.session.uploadFile(path, request);
when I try to build my app, it will show the error:
TypeError: Cannot set property 'NAMESPACE' of undefined
The line of error is exactly this line:
var task = this.session.uploadFile(path, request);
any idea?

I've got a solution for you. To upload image using nativescript background http is now easy using a file stream method on your backend server.
https://www.ekpotoliberty.com/read/NativeScript-Image-Uploading-to-NodeJs-Api-+-Cloudinary-using-NativeScript-Background-HTTP/5dad52c76dc813685f8da26f
Follow the link above this will help you get through for nativescript core.

Related

NativeScript Vue send request with form data (multipart/form-data)

I have a case in my application where I need to send data as form data to a server. The data includes a message and an optional list of files. The problem I'm facing is that when sending the request it's not being formed properly.
Request Payload
Expected (sample with the same request in the browser)
Actual (resulting request when running in NativeScript)
The actual result is that the payload is somehow being URL encoded.
Code example
sendData({ id, message, files }) {
const config = {
headers: {
'Content-Type': 'multipart/form-data'
}
};
const payload = new FormData();
payload.append('message', message);
if (files && files.length > 0) {
files.forEach((file) => {
payload.append(`files`, file, file.name);
});
}
return AXIOS_INSTANCE.post(
`/api/save/${id}`,
payload,
config
);
}
As you can see from the above, I'm using axios and also I'm trying to use FormData to format the data. From my research it seems that NativeScript used to not support binary data via XHR - however looking at this merge request on GitHub it looks like it's been fixed about a year ago.
So my suspicion is that I'm doing something wrong, maybe there's an alternative to using FormData, or else I shouldn't use axios for this particular request?
Version Numbers
nativescript 6.8.0
tns-android 6.5.3
tns-ios 6.5.3
Nativescript's background-http supports multipart form data.
See below for how its configured to do multipart upload
var bghttp = require("nativescript-background-http");
var session = bghttp.session("image-upload");
var request = {
url: url,
method: "POST",
headers: {
"Content-Type": "application/octet-stream"
},
description: "Uploading "
};
var params = [
{ name: "test", value: "value" },
{ name: "fileToUpload", filename: file, mimeType: "image/jpeg" }
];
var task = session.multipartUpload(params, request);

Expo React Native upload an image to Laravel in backend

I am fairly new to coding and I'm in the learning phase for both React Native and Laravel. I was working on some practice project and I needed to upload an image from my React Native app to the Laravel server and from the server I could save it on a cloud or something. I can upload and display the image on the app using expo-image-picker but I just can't seem to get it to post it to the server using formData.
Also, why is that when I console.log formData why is it showing an empty object?
My code to loading the image and uploading it:
pickImage = async () => {
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.All,
allowsEditing: true,
aspect: [4, 3],
quality: 1,
});
console.log(result);
if(!result.cancelled)
{
this.setState({
image : result.uri
})
}
// ImagePicker saves the taken photo to disk and returns a local URI to it
let localUri = result.uri;
//console.log("localUri:", localUri)
let filename = localUri.split('/').pop();
console.log("filename:", filename)
// extract the filetype
//let fileType = localUri.substring(localUri.lastIndexOf(".") + 1);
//console.log(fileType)
let fileType = localUri.substring(localUri.lastIndexOf(":") + 1,localUri.lastIndexOf(";")).split("/").pop();
console.log("type:", fileType)
let formData = new FormData();
formData.append("photo", {
uri : localUri,
name: `photo.${fileType}`,
type: `image/${fileType}`
});
console.log("formdata", formData)
let options = {
method: "POST",
body: formData,
headers: {
Accept: "application/json",
"Content-Type": "multipart/form-data"
}
};
let response = await fetch(`${this.props.url}imagetest`, options)
result = await response.json()
console.log(result)
My simple code for api.php in Laravel is:
Route::post("/imagetest", function (Request $request) {
return ["uploaded" => $request->hasFile("photo")];
});
Found the solution at
send image using Expo
The problem I was having, I was testing it by running the code on web, when I ran it on the device I could see the formdata as well as the image was been uploaded too

Parse Server - How to delete image file from the server using cloud code

How can I delete an image's file from the server using Parse Cloud Code. I am using back4app.com
After Deleting Image Row
I am getting the images urls, then calling a function to delete the image using its url
Parse.Cloud.afterDelete("Image", function(request) {
// get urls
var imageUrl = request.object.get("image").url();
var thumbUrl = request.object.get("thumb").url();
if(imageUrl!=null){
//delete
deleteFile(imageUrl);
}
if(thumbUrl!=null){
//delete
deleteFile(thumbUrl);
}
});
Delete the image file from the server
function deleteFile(url){
Parse.Cloud.httpRequest({
url: url.substring(url.lastIndexOf("/")+1),
method: 'DELETE',
headers: {
'X-Parse-Application-Id': 'xxx',
'X-Parse-Master-Key': 'xxx'
}
}).then(function(httpResponse) {
console.log(httpResponse.text);
}, function(httpResponse) {
console.error('Request failed with response code ' + httpResponse.status);
});
}
for security reasons, not is posible to delete directly the image from Back4App, using DELETE from SDK or REST API. I believe that you can follow the guide below:
https://help.back4app.com/hc/en-us/articles/360002327652-How-to-delete-files-completely-
After struggling with this for a while it seems to be possible through cloud function as mentioned here. One need to use MasterKey in the cloud code:
Parse.Cloud.define('deleteGalleryPicture', async (request) => {
const {image_id} = request.params;
const Gallery = Parse.Object.extend('Gallery');
const query = new Parse.Query(Gallery);
try {
const Image = await query.get(image_id);
const picture = Image.get('picture');
await picture.destroy({useMasterKey: true});
await Image.destroy();
return 'Image removed.';
} catch (error) {
console.log(error);
throw new Error('Error deleting image');
}
});
For me it was first confusing since I could open the link to that file even after I deleted the reference object in the dashboard, but then I found out that the dashboard is not calling Parse.Cloud.beforeDelete() trigger for some reason.
Trying to download the data from the url after deleting the file through the cloud code function returns 0kB data and therefore confirms that they were deleted.

How to create file of user selected image

I am developing cross platform app with nativescript, I get a problem with getting user selected image from gallery, the library I used return user selected image path. It is very easy in android, it is my code for create File for user selected image that I used in android.
String File_Path = "/storage/emulated/0/Pictures/Screenshots/Screenshot_20171016-173404.png"
File file = new File(File_Path);
The reason I need to create File of user selected image is I will need to send user selected image as a File in Multipar/FormData.
I tried many ways can't find soluction. Any suggestion greatly appreciated.
Thanks
It is my sample code for formdata
The answer above works, however another option would be to convert the selected image to a Base64String and treat it as any other string.
To do that just create a new ImageSource from file path and than simply use the toBase64String method provided.
Simlpy pass the format (jpg, png etc) and you're all set
Use nativescript background http, pass the path to this function
viewModel.uploadImage = function (imageUrl) {
var token = applicationSettings.getString("accessToken");
var form = new FormData();
form.append("file", imageUrl);
var bghttp = require("nativescript-background-http");
var session = bghttp.session("image-upload");
var request = {
url: <url>,
method: "POST",
headers: {
"Content-Type": "application/octet-stream",
"File-Name": "somename",
"Authorization": token
},
description: "image for something"
};
var params = [
{ name: "somename", value: "value" },
{ name: "fileToUpload", filename: imageUrl, mimeType: 'image/jpeg' }
];
let task = session.multipartUpload(params, request);
return task;
}

Difficulty creating a functional Angular2 post

I'm trying to send a post request to another service (a Spring application), an authentication, but I'm having trouble constructing a functional Angular2 post request at all. I'm using this video for reference, which is pretty new, so I assume the information still valid. I'm also able to execute a get request with no problems.
Here's my post request:
export class LogIn {
authUser: string;
authPass: string;
token: any;
constructor(private _http:Http){}
onSubmit() {
var header = new Headers()
var json = JSON.stringify({ user: this.authUser, password: this.authPass })
var params2 = 'user=' + this.authUser + '&password=' + this.authPass
var params = "json=" + json
header.append('Content-Type', 'application/x-www-form-urlencoded')
this._http.post("http://validate.jsontest.com", params, {
headers: header
}).map(res => res.json())
.subscribe(
data => this.token = JSON.stringify(data),
err => console.error(err),
() => console.log('done')
);
console.log(this.token);
}
}
The info is being correctly taken from a form, I tested it a couple of times to make sure. I am also using two different ways to build the json (params and params2). When I try to send the request to http://validate.jsontest.com, the console prints undefined where this.token should be. When I try to send the request to the Spring application, I get an error on that side:
Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported
Does anyone know what I'm doing wrong?
In fact you need to use the GET method to do that:
var json = JSON.stringify({
user: this.authUser, password: this.authPass
});
var params = new URLSearchParams();
params.set('json', json);
this._http.get("http://validate.jsontest.com", {
search: params
}).map(res => res.json());
See this plunkr: http://plnkr.co/edit/fAHPp49vFZJ8OuPC1043?p=preview.

Resources