I searched and searched and asked on slack and asked on the NS FaceBook group and everything I could think of to figure this out. I finally pieced it together and it’s working. So do you want to let your app users take a picture with their camera, or use one in their library for something and you need that photo stored on your web server? We let users take before/progress/after pics from using our device. We want to store these photos so we can see results ourselves and request use from our users for advertisements. So here’s how you do it.
You need to make sure and import your camera ui and also this plugin. It’s extremely awesome and works great. You can get it by running
tns plugin add nativescript-background-http
EDIT: For some reason when I put this on an actual device it wouldn’t save the photos. When on the actual phone it has a problem with using knownFolders.currentApp() and a custom folder, so I change that line from
fs.knownFolders.currentApp().path + “/saved_images“;
and it worked just fine.
After setting that up use the below code, or whatever parts of it you’d like, to make the NS function and push the upload to your server. A couple notes though, I use a folder called /saved_images in my /app project directory to store the files before sending. I’m not sure this is necessary but I wanted to resize to a maximum of 800px wide or height while retaining proportion. It is extremely important this directory is created if you use this filepath or your script will fail and you won’t know why because error logging here doesn’t do anything.
Also, I store a global configuration variable for my api’s URL, so I use url: config.apiUrl in my request options.
Saving The Image In PHP
So the config.apiUrl points directly to my php file (ex:server.com/apifile.php). In this file you need to access file_get_contents(‘php://input’) to access the streamed data coming in. This is how you work with forms submitted using content type “application/octet-stream” to get the file data. With this data you can simply save it however you’d like using file_put_contents. There’s other security concerns you will need to address that I’m not going over here as they are different all different applications of this process. But here’s a quick, simple line for saving the image to a /uploads/ directory:
$all_headers = apache_request_headers();
$newimg = file_put_contents('uploads/' . $all_headers['File-Name'], file_get_contents('php://input'));
Now your image has been saved!
Additional User Data Needed
If you are storing this image and attaching it to a user or any other kind of data you can pass these as header fields just as you did the File-Name. In your JS just under the line:
Add a comma and put the next field you might need such as: