this is my Code Please help me this is my code... My web service in .net how i pass image using java script and get in .net Web service and store in Folder and get it back again. i had tried this Min. 3 hours but i failed to get solution please help me...
// Wait for Cordova to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// Cordova is ready
//
function onDeviceReady() {
// Retrieve image file location from specified source
navigator.camera.getPicture(uploadPhoto,
function(message) { alert('get picture failed'); },
{ quality: 50,
destinationType: navigator.camera.DestinationType.FILE_URI,
sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY }
);
}
function uploadPhoto(imageURI) {
var options = new FileUploadOptions();
options.fileKey="file";
options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
options.mimeType="image/jpeg";
var params = {};
params.value1 = "test";
params.value2 = "param";
options.params = params;
var ft = new FileTransfer();
alert(imageURI);
ft.upload(imageURI, encodeURI("http://www.gameworld.co.in/useImage"), win, fail, options);
}
function win(r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
}
function fail(error) {
alert("An error has occurred: Code = " + error.code);
console.log("upload error source " + error.source);
console.log("upload error target " + error.target);
}
if you have other solution then please tell Me...
Thanks
You need to make use of function to get the actual path using
window.resolveLocalFileSystemURI(imguri, resolveOnSuccess, fsFail);
So your code would look like
var fileuri ="";
function uploadPhoto(imageURI) {
window.resolveLocalFileSystemURI(imageURI, resolveOnSuccess, fsFail)
var fileName = fileuri.substr(fileuri.lastIndexOf('/') + 1);
options.fileName = fileName;
// your remaining code
}
function resolveOnSuccess(entry) {
fileuri = entry.toURL();
//console.log(fileuri);
}
function fsFail(message) {
alert(message);
}
Related
I'm using the Phonegap file transfer plugin to upload a picture to the server. However I am getting error code: 1 (FileTransferError.FILE_NOT_FOUND_ERR). I've tested my server code with POSTMAN and I can upload and image successfully. However I get that error with the plugin. This is my code. The file is declared from "camera_image.src" and I can see the image when I append this to the src of an image on the fly. Any contributions? How is this code not perfect?
var fileURL = camera_image.src;
alert(fileURL);
var win = function (r) {
temp.push(r.response);
statusDom.innerHTML = "Upload Succesful!";
}
var fail = function (error) {
alert("An error has occurred: Code = " + error.code + " | Source:" + error.source + " | Target:" + error.target );
statusDom.innerHTML = "Upload failed!";
}
var options = new FileUploadOptions();
options.fileKey = "properties_photo";
options.fileName=fileURL.substr(fileURL.lastIndexOf('/') + 1);
options.headers = {
Connection: "close"
};
var params = {};
params.value1 = "test";
params.value2 = "param";
options.params = params;
var ft = new FileTransfer();
statusDom = document.querySelector('#status');
ft.onprogress = function(progressEvent) {
if (progressEvent.lengthComputable) {
var perc = Math.floor(progressEvent.loaded / progressEvent.total * 100);
statusDom.innerHTML = perc + "% uploaded...";
console.log(perc);
} else {
if(statusDom.innerHTML == "") {
statusDom.innerHTML = "Loading";
} else {
statusDom.innerHTML += ".";
}
}
};
ft.upload(fileURL, encodeURI("http://cloud10.me/clients/itsonshow/app/image_upload_process.php"), win, fail, options);
I had this problem because of spaces in the path or filename of the file to be uploaded.
You need to ensure the plugin isn't being passed a fileURL with %20 in the URL.
Somehow I keep getting an "error code 5" when trying to set the following right.
What I want to do, is copy an existing file from the assets in android to an accessible spot on the android device to be able to share it across other apps (like mail).
Here is my code example:
window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
var storagefolder = cordova.file.dataDirectory;
var storagefolderpointer;
console.log("storage folder: " + storagefolder);
// Check for support.
if (window.requestFileSystem) {
console.log("filesystem beschikbaar");
var getFSfail = function () {
console.log('Could not open filesystem');
};
var getFSsuccess = function(fs) {
var getDIRsuccess = function (dir) {
console.debug('Got dirhandle');
cachedir = dir;
fileurl = fs.root.fullPath + '/' + storagefolder;
storagefolderpointer = dir;
};
var getDIRfail = function () {
console.log('Could not open directory');
};
console.debug('Got fshandle');
FS = fs;
FS.root.getDirectory(storagefolder, {create:true,exclusive:false}, getDIRsuccess, getDIRfail);
};
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, getFSsuccess, getFSfail);
setTimeout(function() {
console.log("directory beschikbaar");
var suc = function(entry){
var goe = function(){
console.log("copy success");
};
var fou = function(){
console.log("copy NOT NOT success");
};
entry.copyTo(storagefolder, "vcard.vcf", goe, fou);
};
var fai = function(e){
console.log("fail getFile: " + e.code);
};
window.resolveLocalFileSystemURL(storagefolderpointer + "www/visitekaart/vcard.vcf", suc, fai);
}, 1000);
} else {
console.log("filesystem NOT NOT NOT available");
}
have you use cordovaFile plugin instead?,you can use blob to read the content of your files than write a new one on android sdcard using cordovaFile plugin
$cordovaFile.writeFile('appdata/file.txt', blob, 0).then(function(fileEntry) {
//success
}, function(err) {
//err
}
Iam unable to upload pictures to a webserver with PHP backend.
My cordova camera script is able to taking the picture and show the picture in small size. But it is not able to upload an image. I dont no why. I call the function photoUpload(); and set the a onClick-event in the button like
<button class="camera-control" onclick="photoUpload();">UPLOAD</button>
Here is my JavaScript, whats wrong with it?
var pictureSource;
var destinationType;
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
pictureSource = navigator.camera.PictureSourceType;
destinationType = navigator.camera.DestinationType;
}
function clearCache() {
navigator.camera.cleanup();
}
var retries = 0;
function onCapturePhoto(fileURI) {
$("#cameraPic").attr("src", fileURI);
var win = function (r) {
clearCache();
retries = 0;
navigator.notification.alert(
'',
onCapturePhoto,
'Der Upload wurde abgeschlossen',
'OK');
console.log(r);
}
var fail = function (error) {
navigator.notification.alert(
'Bitte versuchen Sie es noch einmal.',
onCapturePhoto,
'Ein unerwarteter Fehler ist aufgetreten',
'OK');
console.log("upload error source " + error.source);
console.log("upload error target " + error.target);
if (retries == 0) {
retries ++
setTimeout(function() {
onCapturePhoto(fileURI)
}, 1000)
} else {
retries = 0;
clearCache();
alert('Fehler!');
}
}
function photoUpload() {
var fileURI = $("#cameraPic").attr("src");
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = fileURI.substr(fileURI.lastIndexOf('/') + 1);
options.mimeType = "image/jpeg";
options.chunkedMode = false;
var params = new Object();
params.fileKey = "file";
options.params = {}; // eig = params, if we need to send parameters to the server request
var ft = new FileTransfer();
ft.upload(fileURI, encodeURI("http://xxxx/app/upload.php"), win, fail, options);
}
}
function capturePhoto() {
navigator.camera.getPicture(onCapturePhoto, onFail, {
quality: 50,
destinationType: destinationType.FILE_URI
});
}
function getPhoto(source) {
navigator.camera.getPicture(onPhotoURISuccess, onFail, {
quality: 50,
destinationType: destinationType.FILE_URI,
sourceType: source });
}
function onFail(message) {
alert('Failed because: ' + message);
}
Look your function photoUpload is located in the function onCapturePhoto! you need to move function photoUpload on the top level.
window.photoUpload = function() {
var fileURI = $("#cameraPic").attr("src");
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = fileURI.substr(fileURI.lastIndexOf('/') + 1);
options.mimeType = "image/jpeg";
options.chunkedMode = false;
var params = new Object();
params.fileKey = "file";
options.params = {}; // eig = params, if we need to send parameters to the server request
var ft = new FileTransfer();
ft.upload(fileURI, encodeURI("http://xxxx/app/upload.php"), win, fail, options);
}
And the better way to do it like:
<button class="camera-control" id="photoUploadButton;">UPLOAD</button>
document.getElementById("photoUploadButton").addEventListener("click", photoUpload);
I am trying to make a plugin for Mozilla which prints simple SSL details like Name and certificate is valid till what date.
Here is my CODE :
var data = require("sdk/self").data;
var text_entry = require("sdk/panel").Panel({
width: 412,
height: 400,
contentURL: data.url("text-entry.html"),
contentScriptFile: data.url("get-text.js")
});
require("sdk/widget").Widget({
label: "Text entry",
id: "text-entry",
contentURL: "http://www.mozilla.org/favicon.ico",
panel: text_entry,
});
text_entry.on("show", function() {
text_entry.port.emit("show");
});
text_entry.port.on("text-entered", function (text) {
console.log(text);
var requrl = require("sdk/tabs").activeTab.url;
console.log(requrl);
const {Ci,Cc} = require("chrome");
//var req = new XMLHttpRequest();
var req = Cc["#mozilla.org/xmlextras/xmlhttprequest;1"].createInstance(Ci.nsIXMLHttpRequest);
req.open('GET', requrl, false);
req.onload = function(e) {
console.log(req);
let channel = req.channel;
console.log(requrl);
if (! channel instanceof Ci.nsIChannel) {
console.log("No channel available\n");
return;
}
console.log(requrl);
var secInfo = req.securityInfo;
var cert = secInfo.QueryInterface(Ci.nsISSLStatusProvider).SSLStatus.QueryInterface(Ci.nsISSLStatus).serverCert ;
var validity = cert.validity.QueryInterface(Ci.nsIX509CertValidity);
console.log(requrl);
console.log("\tCommon name (CN) = " + cert.commonName + "\n");
console.log("\tOrganisation = " + cert.organization + "\n");
console.log("\tIssuer = " + cert.issuerOrganization + "\n");
console.log("\tSHA1 fingerprint = " + cert.sha1Fingerprint + "\n");
console.log("\tValid from " + validity.notBeforeGMT + "\n");
console.log("\tValid until " + validity.notAfterGMT + "\n");
};
});
It says, XMLHttpRequest is not defined. Also the channel structure is empty when printed to console.
Not exactly sure where your code is broken or why (as I'm to lazy to replicate the missing pieces like the text-entry.html).
Anyway, here is a fast test that works for me in both, and SDK add-on and Scratchpad:
// Save as your main.js.
// Alternatively execute in a Scratchpad in about:newTab.
var sdk = false;
if (!("Cc" in this)) {
try {
// add-on SDK version
this.Cc = require("chrome").Cc;
this.Ci = require("chrome").Ci;
this.log = console.error.bind(console);
this.sdk = true;
log("using SDK");
}
catch (ex) {
// Scratchpad on about:newtab version
this.Cc = Components["classes"];
this.log = console.log.bind(console);
log("using scratchpad");
}
}
let r = Cc["#mozilla.org/xmlextras/xmlhttprequest;1"]
.createInstance(Ci.nsIXMLHttpRequest);
r.open("GET", "https://tn123.org/");
r.onloadend = function(e) {
let ok = "OK";
try {
log(e);
// Note: instanceof is an implicit QueryInterface!
log(this.channel instanceof Ci.nsIChannel);
log(this.channel.securityInfo instanceof Ci.nsISSLStatusProvider);
let status, cert;
log(status = this.channel.securityInfo.SSLStatus);
log(status.cipherName);
log(cert = status.serverCert);
log("Common name (CN) = " + cert.commonName);
log("Organisation = " + cert.organization);
log("Issuer = " + cert.issuerOrganization);
log("SHA1 fingerprint = " + cert.sha1Fingerprint);
log("Valid from " + cert.validity.notBeforeGMT);
log("Valid until " + cert.validity.notAfterGMT);
for (let k of Object.keys(cert)) {
if (k[0].toUpperCase() === k[0]) {
// skip constants
continue;
}
let v = cert[k];
if (typeof v === "function") {
continue;
}
log(k + ": " + v);
}
}
catch (ex) {
log("Caught exception", ex);
ok = ex;
}
if (sdk) {
require("notifications").notify({
title: "Test done",
text: "HTTPS test done; result=" + ok
});
}
log("HTTPS test done; result=" + ok);
};
r.send();
PS: I'm using console.error in the SDK, because:
If you're developing your add-on using the Extension Auto-installer,
then the add-on is installed in Firefox, meaning that messages will
appear in the Browser Console. But see the discussion of logging
levels: by default, messages logged using log(), info(), trace(), or
warn() won't be logged in these situations.
Have you written this in the content script? If so, you can't make requests from the content script (which is why it says it does not exist). You need to write this in main.js. If you want to communicate with your content script (html, window, etc) you'll have to use message passing: port.emit and addon.emit to send messages and port.on and addon.on to listen for messages.
I am using PhoneGap, and uploading a file (using a HTTP POST) like this,
function uploadSingleFile()
{
var ft = new FileTransfer();
// set up parameters etc
ft.upload(imageName, "http://serviceaddress/UploadFile.ashx", win, fail, options);
}
function win(r)
{
// success callback
}
I am wanting to upload muliple files, so in the success callback I want to call the uploadSingleFile to move onto the next file.
How can I store which file I am up to? I am using the localStorage to store the file names. So I would want to do this,
upload file localStorage.file0
upload file localStorage.file1
upload file localStorage.file2
So all I would need to do would be to store the number on the end, 0, 1, etc of where we are up to. Do I need to use a global variable? Seems messy.
If only I could pass through to the success callback a number as a additional parameter?
Hmmm. Is the problem worth doubting? Just store an array of file names and use JSON.stringify / JSON.parse for conversion between array and string.
function uploadSingleFile(fileName) {
var ft = new FileTransfer();
ft.upload("fileUrl",
"server",
function (result , fileName) {
console.log(fileName + ' has been uploaded successfully to server');
},
function (error) {
console.log(error);
},
{fileName: fileName, fileKey: "file"});
}
function uploadFiles() {
var files = JSON.parse(localStorage.files);
for(var i=0; i < files.length; i++) {
uploadSingleFile(files[i]);
}
}
You can send the index of file as parameter to uploadSingleFile() then using it in console.log()
First add all your images to array :
var TemplstImg = [];
function UploadImages()
{
var lstImages = [localStorage.file0,localStorage.file1,localStorage.file2];
TemplstImg=lstImages ;
if (TemplstImg.length > 0) {
var img = TemplstImg.pop();
uploadPhoto(img);
}
}
function uploadPhoto(imageURI) {
imageURI = imageURI.ImageFile;
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = imageURI.substr(imageURI.lastIndexOf('/') + 1);
options.mimeType = "image/jpeg";
var params = {};
params.value1 = "test";
params.value2 = "param";
options.params = params;
var ft = new FileTransfer();
ft.upload(imageURI, yourServerPath, winImg, failImg,options);
}
function winImg(r) {
if (TemplstImg.length == 0) {
alert ('Done , all files was uploaded');
} else {
var img = TemplstImg.pop();
uploadPhoto(img);
}
}
function failImg(error) {
alert("failImg An error has occurred: Code = " + error.code);
console.log("upload error source " + error.source);
console.log("upload error target " + error.target);
}