What is the best way to save my photo on the server?

Currently, I am developing an application using Phonegap that is specific for Android, iOS, and Windows phone platforms. As part of the app functionality, I am utilizing the Camera API to capture images on the user's device. However, at the moment, these captured pictures are not being stored locally and will be deleted upon reopening the app. To address this issue, I want to implement a feature that allows me to store these pictures on my server in formats like .jpeg using JavaScript/HTML. Can anyone guide me on how to create and save these image files?

var pictureSource; // source of the picture var destinationType; // determines the format of the returned value

// Wait for the device API libraries to load
//
document.addEventListener("deviceready",onDeviceReady,false);

// Device APIs are now accessible
//
function onDeviceReady() {
    pictureSource = navigator.camera.PictureSourceType;
    destinationType = navigator.camera.DestinationType;
}

// Function called when a photo is successfully retrieved as base64 data
//
function onPhotoDataSuccess(imageData) {
  // Un-comment to view the base64-encoded image data
  // console.log(imageData);

  // Get the image element
  //
  var smallImage = document.getElementById('smallImage');

  // Make image elements visible
  //
  smallImage.style.display = 'block';

  // Display the captured photo
  //
  smallImage.src = "data:image/jpeg;base64," + imageData;
}

// Function called when a photo file URI is successfully retrieved
//
function onPhotoURISuccess(imageURI) {
  // Un-comment to view the image file URI
  // console.log(imageURI);

  // Get the image element
  //
  var largeImage = document.getElementById('largeImage');

  // Make image elements visible
  //
  largeImage.style.display = 'block';

  // Display the captured photo
  //
  largeImage.src = imageURI;
}

// Function called by a button to capture a photo
//
function capturePhoto() {
  // Capture a photo using the device camera and retrieve it as a base64-encoded string
  navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 50,
    destinationType: destinationType.DATA_URL });
}

// Function called by a button to capture and edit a photo
//
function capturePhotoEdit() {
  // Capture a photo using the device camera with editing allowed, and retrieve it as a base64-encoded string
  navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 20, allowEdit: true,
    destinationType: destinationType.DATA_URL });
}

// Function called by a button to get a photo from a specified source
//
function getPhoto(source) {
  // Retrieve the image file location from the specified source
  navigator.camera.getPicture(onPhotoURISuccess, onFail, { quality: 50,
    destinationType: destinationType.FILE_URI,
    sourceType: source });
}

// Function called if an error occurs
//
function onFail(message) {
  alert('Failed because: ' + message);
}

Answer №1

to retrieve the FILE_URI and then upload it to your server using php, you can follow this example:

Example code for Phonegap:

function uploadImage(imageURI) {
            var options = new FileUploadOptions();
            options.fileKey="file";
            options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
            options.mimeType="image/jpeg";

            var params = new Object();
            params.value1 = "test";
            params.value2 = "param";

            options.params = params;
            options.chunkedMode = false;

            var ft = new FileTransfer();
            ft.upload(imageURI, "http://yourdomain.com/upload.php", successCallback, failureCallback, options);
        }

        navigator.camera.getPicture(uploadImage, function(message) {
       alert('Failed to get picture');
    },{
            quality: 50, 
            destinationType: navigator.camera.DestinationType.FILE_URI,
            sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY
        }
            );

PHP Script (upload.php):

<?php
print_r($_FILES);
$new_image_name = "newimagename.jpg";
move_uploaded_file($_FILES["file"]["tmp_name"], "/srv/www/upload/".$new_image_name);
?>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

code shatters console.log()!

I'm confused about the output I'm seeing: let frenchWords; const fs = require('fs'); const data = fs.readFileSync('frenchVerbsList.txt', 'utf8'); frenchWords = data.split('\n'); console.log(Array.isA ...

Cufon failing to load following an ajax call

At first, cufon is used to replace the text on the main page. However, when another page file is loaded, cufon does not apply its replacement to the newly loaded content. Why is that? I tried adding cufon.refresh(); as the last function in the chain. I c ...

Error encountered: Difficulty rendering Vue 3 components within Google Apps Script

Currently delving into Vue and Vue 3 while coding an application on Google Apps Script. Following tutorials from Vue Mastery and stumbled upon a remarkable example by @brucemcpherson of a Vue 2 app functioning on GAS, which proved to be too challenging in ...

Storing Data with expressjs/session in NodeJS

My development project involves 3 files: app.js, index.js (routes), and Users.js (controller). Upon successful user login (verification between POST data and the database), I aim to store information in a session using expressjs/session. Below is how I c ...

The window.open function is returning a null value after attempting to open the specified

Is there a way to prevent users from opening more than one IFrame window for my application? I have included the following code: <html> <head> <title>Testing Window Opening Limitation</title> <meta http-equiv="Content-Type" cont ...

Firefox is unable to display SWF files

My code snippet: <div id="sw" style="cursor:pointer" > <object id="swfobj" type="application/x-shockwave-flash"> </object> The JavaScript part: function openfile(filePath) { $("#swfobj").attr("data", filePath); $("#sw ...

Movement and physics mechanics for players using Physi.js

As I work on a basic game using Three.js for rendering and Physijis for physics, my question can be applied to games in general. In games, players often display movement that appears disconnected from the physics engine. They can accelerate instantly and ...

How to properly handle sending an empty post request in Angular 2

My current issue revolves around attempting to send data from my application to the server using a POST request, however, the server seems to be receiving empty POST data. This is the function responsible for sending the data: private headers = new Heade ...

The Most Seamless Approach to Incorporating Successive UI Animations

I am working on a game where I need my character to jump by increasing the origin.y by 50 and then reverse the animation. I have tried two methods to achieve this: Approach 1: [UIView animateWithDuration:1.0 delay:0.0 ...

Obtain the chosen option from an HTML select element by utilizing JavaScript

This is my HTML snippet: <div id="detail"> <div class="d_left"> Page <strong>1</strong> of 107 </div> <div class="d_center"> <table> <tr> <td><a href="#">Previous&l ...

Creating randomized sequences using JavaScript

One of my hobbies involves organizing an online ice hockey game league where teams from different conferences compete. It's important to me that every team gets an equal number of home and away matches throughout the season. To simplify this task, I&a ...

Is it possible for the original object to be altered when passing it as a parameter to a function in a different file?

When you update an object passed as a parameter, will the updates be reflected "upwards" if the method receiving the parameter is in a different file? Or will the object retain its own context despite being passed down? ...

Adding jQuery and other libraries to Typescript for optimal functionality

After spending days researching and struggling, I am reaching out here for clarification on the process of importing a library in Typescript. I used to just add the script tag and everything would work fine. Now that I am working on building a MEAN-Stack ...

Concerns about the performance of NSUserDefaults

My current challenge involves a fast-paced game where user progress needs to be saved constantly. The game progresses rapidly, with significant user progression occurring up to 6 times a second. To handle this, I am storing progression variables in NSUserD ...

Guess the Number Game with while Loop

I have a project where I need to limit guesses to 10, display the guessed number, and keep those results on the screen after each game without replacing the previous guesses. Each set of guesses should be numbered to show how many guesses have been made us ...

Does the ES6 specification include .finally()?

Many Promise libraries such as Q or Bluebird have a method called .finally that is executed on both success and error. Does the ES6 promise also include this method? I haven't been able to find it. It doesn't seem to be present in Babel (6to5). ...

Encountering the error message ERR_CONNECTION_TIMED_OUT while using Vue CLI

Currently, I am venturing into the world of Vuex and attempting to incorporate some API requests using this state management pattern. Here is the structure I have set up: Component.Vue export default { created() { this.$store.dispatch('getDat ...

Having trouble determining why the design is not displaying correctly

I'm currently working on a calendar webpage, and everything looks perfect until I add the new JavaScript element. Suddenly, the numbers in the first row start behaving strangely. I've tried to troubleshoot but can't seem to figure out what&a ...

Post-installation of NPM, configuring CA certificates on Windows system

TLDR; Is there a way to seamlessly set NODE_EXTRA_CA_CERTS in a Windows environment for NPM packages' post-install scripts without requiring system changes, configuration file modifications, or admin-level permissions? Details This issue has been f ...

Interactive html5 canvas game with swiping mechanism

Currently, I am in the research phase for a new HTML5 canvas game that I want to create as a personal project to enhance my skills. Surprisingly, I have not been able to find any valuable articles or tutorials online about creating swipe-based games. The ...