Image previewing before upload in phonegap - javascript

I know there are some answers available already but i really dont understand why thats not working in my case.below is my code for uploading in remote server.I am using phonegap and jquery mobile.Only problem is image does not shows on the page before uploading to the server.
<html>
<head>
<title>File Transfer Example</title>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript">
function getImage() {
navigator.camera.getPicture(uploadPhoto, function(message) {
alert('get picture failed');
}, {
quality: 100,
destinationType: navigator.camera.DestinationType.FILE_URI,
sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY
});
}
function uploadPhoto(imageURI) {
document.getElementById("smallImage").src = imageURI
}
function uploadPhoto(imageURI) {
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = imageURI.substr(imageURI.lastIndexOf('/') + 1);
options.mimeType = "image/jpeg";
console.log(options.fileName);
var params = new Object();
params.value1 = "test";
params.value2 = "param";
options.params = params;
options.chunkedMode = false;
var ft = new FileTransfer();
ft.upload(imageURI, "http://abc.in/my.php",
function(result){
console.log(JSON.stringify(result));
alert('success');
}, function(error){
console.log(JSON.stringify(error));
}, options);
}
</script>
</head>
<body>
<button onclick="getImage()">Upload a Photo</button><br>
<img style="width:160px;" id="smallImage" src="" />
</body>
</html>

The imageURI is a pseudo-path, so it might be unavailable on you local HTML page.
You can update the image src after you upload the image.
var ft = new FileTransfer();
ft.upload(imageURI, "http://abc.in/my.php",
function(result){
var data = JSON.stringify(result);
var imageSrc = data.src; // e.g: "http://abc.in/picture.jpg"
document.getElementById("smallImage").src = imageSrc;
},
HTTP URL should work.

After 3 day's i got a solution for my query,problem is simulator,test below code with apk file.Do not waste time on testing simulator's.It won't preview image.
Below code is working for previewing image before upload.
<!DOCTYPE html>
<html>
<head>
<title>Submit form</title>
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8">
var pictureSource; // picture source
var destinationType; // sets the format of returned value
// Wait for device API libraries to load
//
document.addEventListener("deviceready",onDeviceReady,false);
// device APIs are available
//
function onDeviceReady() {
pictureSource = navigator.camera.PictureSourceType;
destinationType = navigator.camera.DestinationType;
}
// Called when a photo is successfully retrieved
//
function onPhotoURISuccess(imageURI) {
// Show the selected image
var smallImage = document.getElementById('smallImage');
smallImage.style.display = 'block';
smallImage.src = imageURI;
}
// A button will call this function
//
function getPhoto() {
// Retrieve image file location from specified source
navigator.camera.getPicture(onPhotoURISuccess, onFail, { quality: 50,
sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY });
}
function uploadPhoto() {
//selected photo URI is in the src attribute (we set this on getPhoto)
var imageURI = document.getElementById('smallImage').getAttribute("src");
if (!imageURI) {
alert('Please select an image first.');
return;
}
//set upload options
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = imageURI.substr(imageURI.lastIndexOf('/')+1);
options.mimeType = "image/jpeg";
options.chunkedMode = false;
options.params = {
firstname: document.getElementById("firstname").value,
lastname: document.getElementById("lastname").value
}
options.headers = {
Connection: "close"
};
var ft = new FileTransfer();
ft.upload(imageURI, encodeURI("http://abc.in/savepng.php"), win, fail,
options);
}
// Called if something bad happens.
//
function onFail(message) {
console.log('Failed because: ' + message);alert('success');
}
function win(r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
alert("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);
}
</script>
</head>
<body>
<button onclick="getPhoto();">Select Photo:</button><br>
<img style="display:none;width:60px;height:60px;" id="smallImage" src="" /><br>
<form id="regform">
First Name: <input type="text" id="firstname" name="firstname"><br>
Last Name: <input type="text" id="lastname" name="lastname"><br>
<input type="button" id="btnSubmit" value="Submit" onclick="uploadPhoto();">
</form>
</body>
</html>

Related

How do I upload images through AJAX after compressing the images?

I have an interface that allows multiple file uploads. The user dumps a set of files on the file element.
The script then sets the height, width and dpi of those images and displays them in a large thumbnail.
That all works fine. If I right-click and save an image, it is now 1600x1600 at 96 dpi. Exactly what I specified.
Now, I need to upload the images through AJAX by creating a new FileList. But how do I specify the filename and the content for the file list?
I have a hidden file element which I'll update with the new file list which will trigger the AJAX.
Here is the HTML and the javascript/jquery:
<form enctype="multipart/form-data" id="frmUploadImage">
<input name="files" type="file" id="imgUpload" class="upload" multiple accept="image/*"/>
</form>
<form enctype="multipart/form-data" id="frmSaveImage" style="display:none">
<input name="files" type="file" id="saveImages" class="upload" multiple accept="image/*"/>
</form>
<input type="button" id="saveIt" value="Save">
<script>
$(`#imgUpload`).on(`change`, function() {
const $fileUpload = $(this);
Array.from($fileUpload.get(0).files).forEach(function(f, i) {
$(`#compressResultsContainer`).append(`<div id="image_${i}_container" class="compressedImageContainer"><img id="source_${i}" style="display:none"/><img id="image_${i}" class="compressedImage" style="width: 200px; height:200px"/><canvas id="canvas_${i}" style="display:none"></canvas><div>`);
let $preview = $(`#source_${i}`);
var reader = new FileReader();
reader.addEventListener(`load`, function(e) {
$preview.attr(`src`, e.target.result);
$preview.on(`load`, function() {
console.log(`loading preview ${i}`);
compressFile(this, i);
});
}, false);
if (f) {
reader.readAsDataURL(f);
}
});
});
function compressFile(loadedData, imgNum) {
var mime_type = `image/jpeg`;
var cvs = document.getElementById(`canvas_${imgNum}`);
cvs.width = 1600;
cvs.height = 1600;
var ctx = cvs.getContext(`2d`).drawImage(loadedData, 0, 0, 1600,1600);
var newImageData = cvs.toDataURL(mime_type, 96);
var result_image_obj = new Image();
result_image_obj.src = newImageData;
$(`#image_${imgNum}`).attr(`src`, result_image_obj.src);
}
// my test function just to see if I can build new form data---
$(`#saveIt`).on(`click`, function() {
let formData = new FormData();
$(`.newCanvas`).each(function() {
let file;
const canvas =document.getElementById($(this).attr(`id`));
canvas.toBlob((blob) => {
console.log(`canvas:`, $(this).attr(`id`));
file = new File([blob], $(this).attr(`filename`), { type: `image/jpeg` });
formData.append(`savedImages`, new File([blob], $(this).attr(`filename`), { type: `image/jpeg` }));
console.log(file);
}, `image/jpeg`);
});
setTimeout(function() { console.log(formData); }, 3000);
});
</script>
I'm basically stuck on how to populate the new FileList with the proper content -- the compressed images and their filename.
You had ONE tiny issue which made nothing to work: looping through the .newCanvas elements when absolutely no element had the class. So the loop squarely didn't run.
There also is a couple "improvements" that can be done... But to have the formData populated, that was the only thing.
So I added class="newCanvas" to <canvas id="canvas_${i}" on that line:
$(`#compressResultsContainer`).append(
`<div id="image_${i}_container" class="compressedImageContainer"><img id="source_${i}" style="display:none"/><img id="image_${i}" class="compressedImage" style="width: 200px; height:200px"/><canvas id="canvas_${i}" class="newCanvas" data-name="${f.name}" style="display:none"></canvas><div>`
);
Notice that I also added a data-name to hold the file name. That information has to be carried by the canvas to later be usable in the .each() loop.
Now about a couple improvements:
You use backticks everywhere. Good practice would be to use them when really needed, like when some templating ${variable} is inside the string...
document.getElementById($(this).attr(id)) is EXACTLY the same as just this.
Except that you've made a jQuery lookup on this to get the id and then used that id to retreive the element using plain JS.
In an .each() loop, this is the element of the current loop.
Within the .toBlob() callback, $(this) no longer is the canvas element. You have to get the informations from the canvas before calling .toBlob()
You used a setTimeout() to wait for the canvas.toblob() results... That is not reliable. I suggest you to use the number of appended files in the formData and compare that with the number of .newCanvas element to process.
That comparison has to be in the canvas.toblob() callback.
So here is the code I suggest you to try.
$(`#imgUpload`).on(`change`, function () {
const $fileUpload = $(this);
Array.from($fileUpload.get(0).files).forEach(function (f, i) {
$(`#compressResultsContainer`).append(
`<div id="image_${i}_container" class="compressedImageContainer"><img id="source_${i}" style="display:none"/><img id="image_${i}" class="compressedImage" style="width: 200px; height:200px"/><canvas id="canvas_${i}" class="newCanvas" data-name="${f.name}" style="display:none"></canvas><div>`
);
let $preview = $(`#source_${i}`);
var reader = new FileReader();
reader.addEventListener(
`load`,
function (e) {
$preview.attr(`src`, e.target.result);
$preview.on(`load`, function () {
console.log(`loading preview ${i}`);
compressFile(this, i);
});
},
false
);
if (f) {
reader.readAsDataURL(f);
}
});
});
function compressFile(loadedData, imgNum) {
var mime_type = `image/jpeg`;
var cvs = document.getElementById(`canvas_${imgNum}`);
cvs.width = 1600;
cvs.height = 1600;
var ctx = cvs.getContext(`2d`).drawImage(loadedData, 0, 0, 1600, 1600);
var newImageData = cvs.toDataURL(mime_type, 96);
var result_image_obj = new Image();
result_image_obj.src = newImageData;
$(`#image_${imgNum}`).attr(`src`, result_image_obj.src);
}
// my test function just to see if I can build new form data---
$(`#saveIt`).on(`click`, function () {
let allCanvas = $(`.newCanvas`)
let canvasCount = allCanvas.length
let formData = new FormData();
allCanvas.each(function () {
let file;
const canvas = this // document.getElementById($(this).attr(`id`));
// Get the filename here
// Because inside the .toBlob callback this and $(this) no longer is the canvas
let canvasName = this.getAttribute("data-name")
canvas.toBlob((blob) => {
console.log(`canvas:`, $(this).attr(`id`));
file = new File([blob], canvasName, { type: `image/jpeg` });
formData.append(
`savedImages`,
file
);
console.log(file);
// Did we procces all canvas?
// This part is to replce your setTimeout
// So here you can call the Ajax
if(formData.getAll("savedImages").length === canvasCount){
// Just formData will print the constructor
//console.log(formData);
console.log(formData.getAll("savedImages"));
}
}, `image/jpeg`);
});
/*
setTimeout(function () {
console.log(formData);
}, 3000);
*/
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form enctype="multipart/form-data" id="frmUploadImage">
<input name="files" type="file" id="imgUpload" class="upload" multiple accept="image/*" />
</form>
<form enctype="multipart/form-data" id="frmSaveImage" style="display:none">
<input name="files" type="file" id="saveImages" class="upload" multiple accept="image/*" />
</form>
<input type="button" id="saveIt" value="Save">
<div id="compressResultsContainer"></div>
I finally had time to get back to this yesterday. This works:
<h1>Image Maintenance</h1><br>
<input name="files" type="file" id="imgProcess" class="upload" multiple accept="image/*"/>
<div id="progressContainer">
<div id="processProgressContainer">
<progress id="processProgress" value="0" style="vertical-align: middle;"></progress>
<span id="processStatus" style="margin-left: 20px;"></span>
</div>
<div id="uploadProgressContainer" style="display:none">
<span style="width: 150px; float:left">Seasonal Upload</span>
<span style="width: 150px; float:left">.Com Upload</span>
<span style="width: 150px; float:left">Repository Upload</span><br style="clear:both"/>
<span style="width: 150px; float:left"><progress id="seasonalProgress" value="0" style="vertical-align: middle;"></progress></span>
<span style="width: 150px; float:left"><progress id="comProgress" value="0" style="vertical-align: middle;"></progress></span>
<span style="width: 150px; float:left"><progress id="repositoryProgress" value="0" style="vertical-align: middle;"></progress></span>
</div>
</div>
<input type="button" id="saveIt" value="Save">
<input type='text' class='chromeAutoInputCatcher' tabindex='-1' name='stupidChromeInputCatcher'></input>
<div id="compressResultsContainer"></div>
<script>
// #ts-nocheck
/* eslint-disable no-undef */
/* eslint-disable max-len */
/* eslint-disable no-invalid-this */
/* eslint-disable require-jsdoc */
/* jshint esversion: 8 */
let kpData;
let repositoryData;
let collection = `524`;
let skuString = `,`;
$(`#imgProcess`).on(`change`, function() {
$(`#uploadProgressContainer`).hide();
$(`#processProgressContainer`).show();
$(`#processProgress`).val(0);
kpData = new FormData();
repositoryData = new FormData();
let rootsku=``;
skuString = `,`;
$(`#compressResultsContainer`).html(``);
//at some point, let's freeze all input until we get done compressing and displaying
const $fileUpload = $(this);
const numPics = $fileUpload.get(0).files.length;
$(`#processProgress`).attr(`max`, numPics);
Array.from($fileUpload.get(0).files).every(f=> {
const thisSku = f.name.split(`-`).slice(0, 4).join(`-`);
if (!rootsku.length) {
rootsku = thisSku.split(`-`)[0];
}
const thisrootsku = thisSku.split(`-`)[0];
if (rootsku !== thisrootsku) {
alert(`found multiple root skus. Aborting`);
$(`#imgProcess`).val(``);
kpData = new FormData();
repositoryData = new FormData();
return false;
}
return true;
});
Array.from($fileUpload.get(0).files).forEach(function(f, i) {
const thisSku = f.name.split(`-`).slice(0, 4).join(`-`);
if (skuString.indexOf(thisSku) < 0) {
skuString += `${thisSku},`;
}
$(`#compressResultsContainer`).append(`<div id="image_${i}_container" class="compressedImageContainer"><img id="source_${i}" style="display:none"/><img id="image_${i}" filename="${f.name}" class="compressedImage" style="width: 200px; height:200px; float:left"/><canvas class="newCanvas" id="canvas_${i}" style="display:none" filename="${f.name}"></canvas><span style="float:left">${f.name}</span></div><br style="clear:both"/>`);
let $preview = $(`#source_${i}`);
var reader = new FileReader();
reader.addEventListener(`load`, function(e) {
$preview.attr(`src`, e.target.result);
$preview.on(`load`, function() {
createImages(this, i);
$(`#processProgress`).val($(`#processProgress`).val() + 1);
$(`#processStatus`).html(`${$(`#processProgress`).val()} of ${numPics} file: ${f.name} `).attr(`filenum`, $(`#processProgress`).val());
if ($(`#processProgress`).val() === numPics) {
getSkus(rootsku);
console.log(`done processing`);
}
});
}, false);
if (f) {
reader.readAsDataURL(f);
}
});
});
function createImages(loadedData, imgNum) {
var mime_type = `image/jpeg`;
var cvs = document.getElementById(`canvas_${imgNum}`);
var cvsName = cvs.getAttribute(`filename`);
//Create the detail version of the image
cvs.width = 800;
cvs.height = 800;
cvs.getContext(`2d`).drawImage(loadedData, 0, 0, 800, 800);
//display the image
var newImageData = cvs.toDataURL(mime_type);
var result_image_obj = new Image();
result_image_obj.src = newImageData;
$(`#image_${imgNum}`).attr(`src`, result_image_obj.src);
//convert the canvase to an uploadable file and append it to our form data
cvs.toBlob((blob) => {
let file = new File([blob], cvsName, { type: `image/jpeg` });
kpData.append(`detail`, file, cvsName);
}, `image/jpeg`,0.96);
//create the general image
cvs.width = 370;
cvs.height = 370;
cvs.getContext(`2d`).drawImage(loadedData, 0, 0, 370, 370);
cvs.toDataURL(mime_type);
cvs.toBlob((blob) => {
let file = new File([blob], cvsName, { type: `image/jpeg` });
kpData.append(`general`, file, cvsName);
}, `image/jpeg`,0.96);
//create the thumbnail
cvs.width = 240;
cvs.height = 240;
cvs.getContext(`2d`).drawImage(loadedData, 0, 0, 240, 240);
cvs.toDataURL(mime_type);
cvs.toBlob((blob) => {
let file = new File([blob], cvsName, { type: `image/jpeg` });
kpData.append(`thumb`, file, cvsName);
}, `image/jpeg`,0.96);
//create the repository image for Amazon, Zulilly, Zappos and our wholesale customers. Zullily has the greatest minimum requirements so we'll use those for everyone
cvs.width = 1600;
cvs.height = 1600;
cvs.getContext(`2d`).drawImage(loadedData, 0, 0, 1600, 1600);
cvs.toDataURL(mime_type);
cvs.toBlob((blob) => {
let file = new File([blob], cvsName, { type: `image/jpeg` });
repositoryData.append(`imgfiles`, file, cvsName);
}, `image/jpeg`, 1);
}
let uploadLocation = `/${scPcFolder}/pc/catalog/`;
saveImages = function(url, formData,server) {
data = formData;
$(`#${server}Progress`).val(0);
$.ajax({
url: url,
cache: false,
contentType: false,
processData: false,
enctype: `multipart/form-data`,
data: data,
type: `POST`,
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) {
myXhr.upload.addEventListener(`progress`, function(e) {
if (e.lengthComputable) {
$(`#${server}Progress`).attr({
value: e.loaded,
max: e.total,
});
}
}, false);
}
return myXhr;
}
}).done(function(data) {
}).fail(function(xhr, textStatus, errorThrown) {
console.log(xhr, textStatus, errorThrown);
}).always(function() {
});
};
function parseReturn(data = ``, nonJson = { beforeData: ``, afterData: `` }) {
data = data.replace(new RegExp(`\r?\n`, `g`), ``).replace(/\t/g, ``);//.replace(/'/g, `''`);
nonJson.beforeData = data.substring(0, data.indexOf(`{`));
nonJson.afterData = data.substring(data.lastIndexOf(`}`) + 1, 99999999);
data = data.substring(data.indexOf(`{`), data.lastIndexOf(`}`) + 1);
try {
return JSON.parse(data);
} catch (e) {
console.log(`error: `, e);
console.log(data);
}
}
$(`#saveIt`).on(`click`, function() {
$(`#processProgressContainer`).hide();
$(`#uploadProgressContainer`).show();
saveImages(`ImageManagement_AJAX.asp?action=saveFiles&uploadLocation=${uploadLocation}&skuString=${skuString}&collection=${collection}`, kpData,`seasonal`);
saveImages(`https://example.com/uploadify/ImageManagement_AJAX.asp?action=saveFiles&uploadLocation=${uploadLocation}`, kpData,`com`);
saveImages(`https://example.com/Image/Upload`, repositoryData,`repository`);
});
function getSkus(rootsku) {
$.ajax({
url: `ImageManagement_AJAX.asp`,
data: { action: `getSkus`, rootsku: rootsku, collection: collection },
type: `POST`,
}).done(function(data) {
//console.log(`data`, data);
let objSkus = parseReturn(data);
objSkus.skus.forEach(function(s) {
s.sku=s.sku.split(`-`).slice(0, s.sku.split(`-`).length - 1).join(`-`);
});
let uniqueSkus = [...new Set(objSkus.skus.map((sku) => sku.sku))];
let html=``;
//make sure every sku has a primary image in this batch of files
uniqueSkus.forEach(function(s) {
if (!$(`.compressedImage[filename="${s}.jpg"]`).length) {
html += `<span style="float:left">${s}</span><span style="float:left; min-width:10px"> </span>`;
console.log(`missing file: `, s);
}
});
if (!html.length) {
html = `Success`;
} else {
html += `<br style="clear:both"/><br/>`;
}
$(`#processStatus`).html(html);
$(`#imgProcess`).val(``);
}).fail(function(xhr, textStatus, errorThrown) {
console.log(xhr, textStatus, errorThrown);
}).always(function() {
});
}
</script>

add shapefile with JS sample code

i want to add shapefile to the map from the folder. i have used JS sample code but it does not work for me.it gives error in response , featurecollection . it doesnot got into request block so i change it to esri request but still code not working
var portalUrl = "https://www.arcgis.com";
esriConfig.defaults.io.proxyUrl = "/proxy/";
on(dojo.byId("uploadForm"), "change", function (event) {
var fileName = event.target.value.toLowerCase();
<!-- if (sniff("ie")) { //filename is full path in IE so extract the file name -->
<!-- var arr = fileName.split("\\"); -->
<!-- fileName = arr[arr.length - 1]; -->
<!-- } -->
if (fileName.indexOf(".zip") !== -1) {//is file a zip - if not notify user
generateFeatureCollection(fileName);
}
else {
alert("Add shapefile as .zip file");
}
});
function generateFeatureCollection (fileName) {
var name = fileName.split(".");
name = name[0].replace("c:\\fakepath\\", "");
var params = {
'name': name,
'targetSR': map.spatialReference,
'maxRecordCount': 1000,
'enforceInputFileSizeLimit': true,
'enforceOutputJsonSizeLimit': true
};
//var extent = scaleUtils.getExtentForScale(map, 40000);
var extent = esri.geometry.getExtentForScale(map, 40000);
var resolution = extent.getWidth() / map.width;
params.generalize = true;
params.maxAllowableOffset = resolution;
params.reducePrecision = true;
params.numberOfDigitsAfterDecimal = 0;
var myContent = {
'filetype': 'shapefile',
'publishParameters': JSON.stringify(params),
'f': 'json',
//'callback.html': 'textarea'
};
esriRequest({
url: portalUrl + '/sharing/rest/content/features/generate',
content: myContent,
form: dojo.byId('uploadForm'),
handleAs: 'json',
load: lang.hitch(this, function (response) {
<!-- if (response.error) { -->
<!-- errorHandler(response.error); -->
<!-- return; -->
<!-- } -->
var layerName = response.FeatureCollection.layers[0].layerDefinition.name;
addShapefileToMap(response.FeatureCollection);
}),
//error: lang.hitch(this, errorHandler)
});
}
function addShapefileToMap (featureCollection) {
var fullExtent;
var layers = [];
arrayUtils.forEach(featureCollection.layers, function (layer) {
var infoTemplate = new InfoTemplate("Details", "${*}");
var featureLayer = new FeatureLayer(layer, {
infoTemplate: infoTemplate
});
featureLayer.on('click', function (event) {
map.infoWindow.setFeatures([event.graphic]);
});
changeRenderer(featureLayer);
fullExtent = fullExtent ?
fullExtent.union(featureLayer.fullExtent) : featureLayer.fullExtent;
layers.push(featureLayer);
});
map.addLayers(layers);
map.setExtent(fullExtent.expand(1.25), true);
}
function changeRenderer (layer) {
//change the default symbol for the feature collection for polygons and points
var symbol = null;
switch (layer.geometryType) {
case 'esriGeometryPoint':
symbol = new PictureMarkerSymbol({
'angle': 0,
'xoffset': 0,
'yoffset': 0,
'type': 'esriPMS',
'url': 'https://static.arcgis.com/images/Symbols/Shapes/BluePin1LargeB.png',
'contentType': 'image/png',
'width': 20,
'height': 20
});
break;
case 'esriGeometryPolygon':
symbol = new SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID,
new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID,
new Color([112, 112, 112]), 1), new Color([136, 136, 136, 0.25]));
break;
}
if (symbol) {
layer.setRenderer(new SimpleRenderer(symbol));
}
}
Well, I went through your jsfiddle and atteched code, I observed few items is missing in it-
important links and js libraries.
dojo /esri component require
map element to display shapefile
map control html to load map element.
Below is the working code(try this)-
var map;
require([
"esri/config",
"esri/InfoTemplate",
"esri/map",
"esri/request",
"esri/geometry/scaleUtils",
"esri/layers/FeatureLayer",
"esri/renderers/SimpleRenderer",
"esri/symbols/PictureMarkerSymbol",
"esri/symbols/SimpleFillSymbol",
"esri/symbols/SimpleLineSymbol",
"dojo/dom",
"dojo/json",
"dojo/on",
"dojo/parser",
"dojo/sniff",
"dojo/_base/array",
"esri/Color",
"dojo/_base/lang",
"dijit/layout/BorderContainer",
"dijit/layout/ContentPane",
"dojo/domReady!"
],
function (
esriConfig, InfoTemplate, Map, request, scaleUtils, FeatureLayer,
SimpleRenderer, PictureMarkerSymbol, SimpleFillSymbol, SimpleLineSymbol,
dom, JSON, on, parser, sniff, arrayUtils, Color, lang
) {
parser.parse();
var portalUrl = "https://www.arcgis.com";
esriConfig.defaults.io.proxyUrl = "/proxy/";
on(dojo.byId("uploadForm"), "change", function (event) {
var fileName = event.target.value.toLowerCase();
<!-- if (sniff("ie")) { //filename is full path in IE so extract the file name -->
<!-- var arr = fileName.split("\\"); -->
<!-- fileName = arr[arr.length - 1]; -->
<!-- } -->
if (fileName.indexOf(".zip") !== -1) {//is file a zip - if not notify user
generateFeatureCollection(fileName);
}
else {
alert("Add shapefile as .zip file");
}
});
map = new Map("mapCanvas", {
basemap: "gray",
center: [-41.647, 36.41],
zoom: 3,
slider: false
});
function generateFeatureCollection (fileName) {
var name = fileName.split(".");
name = name[0].replace("c:\\fakepath\\", "");
var params = {
'name': name,
'targetSR': map.spatialReference,
'maxRecordCount': 1000,
'enforceInputFileSizeLimit': true,
'enforceOutputJsonSizeLimit': true
};
//var extent = scaleUtils.getExtentForScale(map, 40000);
var extent = esri.geometry.getExtentForScale(map, 40000);
var resolution = extent.getWidth() / map.width;
params.generalize = true;
params.maxAllowableOffset = resolution;
params.reducePrecision = true;
params.numberOfDigitsAfterDecimal = 0;
var myContent = {
'filetype': 'shapefile',
'publishParameters': json.stringify(params),
'f': 'json',
'callback.html': 'textarea'
};
esriRequest({
url: portalUrl + '/sharing/rest/content/features/generate',
content: myContent,
form: dojo.byId('uploadForm'),
handleAs: 'json',
load: lang.hitch(this, function (response) {
if (response.error) {
errorHandler(response.error);
return;
}
var featureCollection = {
"layerDefinition": null,
"featureSet": {
"features": [],
"geometryType": "esriGeometryPoint"
}
};
var layerName = response.featureCollection.layers[0].layerDefinition.name;
addShapefileToMap(response.featureCollection);
}),
//error: lang.hitch(this, errorHandler)
});
}
function addShapefileToMap (featureCollection) {
var fullExtent;
var layers = [];
array.forEach(featureCollection.layers, function (layer) {
//for(var i = 0 ; i<=featureCollection.layers.length ; i++){
//featureCollection.layers.forEach(function(layer){
var infoTemplate = new InfoTemplate("Details", "${*}");
var featureLayer = new FeatureLayer(layer, {
infoTemplate: infoTemplate
});
featureLayer.on('click', function (event) {
map.infoWindow.setFeatures([event.graphic]);
});
changeRenderer(featureLayer);
fullExtent = fullExtent ?
fullExtent.union(featureLayer.fullExtent) : featureLayer.fullExtent;
layers.push(featureLayer);
});
map.addLayers(layers);
map.setExtent(fullExtent.expand(1.25), true);
}
function changeRenderer (layer) {
//change the default symbol for the feature collection for polygons and points
var symbol = null;
switch (layer.geometryType) {
case 'esriGeometryPoint':
symbol = new PictureMarkerSymbol({
'angle': 0,
'xoffset': 0,
'yoffset': 0,
'type': 'esriPMS',
'url': 'https://static.arcgis.com/images/Symbols/Shapes/BluePin1LargeB.png',
'contentType': 'image/png',
'width': 20,
'height': 20
});
break;
case 'esriGeometryPolygon':
symbol = new SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID,
new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID,
new Color([112, 112, 112]), 1), new Color([136, 136, 136, 0.25]));
break;
}
if (symbol) {
layer.setRenderer(new SimpleRenderer(symbol));
}
}
});
<link rel="stylesheet" href="https://js.arcgis.com/3.20/dijit/themes/claro/claro.css">
<link rel="stylesheet" href="css/app.css">
<link rel="stylesheet" href="css/fileupload.css">
<link rel="stylesheet" href="https://js.arcgis.com/3.20/esri/css/esri.css">
<script src="https://js.arcgis.com/3.20/"></script>
<form enctype="multipart/form-data" method="post" id="uploadForm">
<div class="field">
<label class="file-upload">
<!-- <span><strong>Choose File</strong></span> -->
<!-- <span align = "center"><Add Shapefile></span> -->
<Label style="font-weight: bold; align = center ">Add Shapefile</label><br></br>
<input type="file" name="file" id="inFile" />
</label>
</div>
</form>
<span class="file-upload-status" style="opacity:1;" id="upload-status"></span>
<div id="fileInfo"> </div>
</div>
</div>
<div id="mapCanvas" data-dojo-type="dijit/layout/ContentPane" data-dojo-props="region:'center'"></div>
Updated JSFiddle- https://jsfiddle.net/vikash2402/f2hxt25d/4/
Note- If still its causing problem then share your shapefile.
Hoping this will help you.
Well, Tried to create another sample-
Here is the working example -
<!DOCTYPE HTML>
<title>Add Shapefile</title>
<link rel="stylesheet" href="https://js.arcgis.com/3.20/dijit/themes/claro/claro.css">
<link rel="stylesheet" href="https://developers.arcgis.com/javascript/3/samples/portal_addshapefile/css/app.css">
<link rel="stylesheet" href="https://developers.arcgis.com/javascript/3/samples/portal_addshapefile/css/fileupload.css">
<link rel="stylesheet" href="https://js.arcgis.com/3.20/esri/css/esri.css">
<script src="https://js.arcgis.com/3.20/"></script>
<script>
var map;
require([
"esri/config",
"esri/InfoTemplate",
"esri/map",
"esri/request",
"esri/geometry/scaleUtils",
"esri/layers/FeatureLayer",
"esri/renderers/SimpleRenderer",
"esri/symbols/PictureMarkerSymbol",
"esri/symbols/SimpleFillSymbol",
"esri/symbols/SimpleLineSymbol",
"dojo/dom",
"dojo/json",
"dojo/on",
"dojo/parser",
"dojo/sniff",
"dojo/_base/array",
"esri/Color",
"dojo/_base/lang",
"dijit/layout/BorderContainer",
"dijit/layout/ContentPane",
"dojo/domReady!"
],
function (
esriConfig, InfoTemplate, Map, request, scaleUtils, FeatureLayer,
SimpleRenderer, PictureMarkerSymbol, SimpleFillSymbol, SimpleLineSymbol,
dom, JSON, on, parser, sniff, arrayUtils, Color, lang
) {
parser.parse();
var portalUrl = "https://www.arcgis.com";
//esriConfig.defaults.io.proxyUrl = "/proxy/";
on(dom.byId("uploadForm"), "change", function (event) {
var fileName = event.target.value.toLowerCase();
if (sniff("ie")) { //filename is full path in IE so extract the file name
var arr = fileName.split("\\");
fileName = arr[arr.length - 1];
}
if (fileName.indexOf(".zip") !== -1) {//is file a zip - if not notify user
generateFeatureCollection(fileName);
}
else {
dom.byId('upload-status').innerHTML = '<p style="color:red">Add shapefile as .zip file</p>';
}
});
map = new Map("mapCanvas", {
basemap: "gray",
center: [-41.647, 36.41],
zoom: 3,
slider: false
});
function generateFeatureCollection (fileName) {
var name = fileName.split(".");
//Chrome and IE add c:\fakepath to the value - we need to remove it
//See this link for more info: http://davidwalsh.name/fakepath
name = name[0].replace("c:\\fakepath\\", "");
dom.byId('upload-status').innerHTML = '<b>Loading… </b>' + name;
//Define the input params for generate see the rest doc for details
//http://www.arcgis.com/apidocs/rest/index.html?generate.html
var params = {
'name': name,
'targetSR': map.spatialReference,
'maxRecordCount': 1000,
'enforceInputFileSizeLimit': true,
'enforceOutputJsonSizeLimit': true
};
//generalize features for display Here we generalize at 1:40,000 which is approx 10 meters
//This should work well when using web mercator.
var extent = scaleUtils.getExtentForScale(map, 40000);
var resolution = extent.getWidth() / map.width;
params.generalize = true;
params.maxAllowableOffset = resolution;
params.reducePrecision = true;
params.numberOfDigitsAfterDecimal = 0;
var myContent = {
'filetype': 'shapefile',
'publishParameters': JSON.stringify(params),
'f': 'json',
'callback.html': 'textarea'
};
//use the rest generate operation to generate a feature collection from the zipped shapefile
request({
url: portalUrl + '/sharing/rest/content/features/generate',
content: myContent,
form: dom.byId('uploadForm'),
handleAs: 'json',
load: lang.hitch(this, function (response) {
if (response.error) {
errorHandler(response.error);
return;
}
var layerName = response.featureCollection.layers[0].layerDefinition.name;
dom.byId('upload-status').innerHTML = '<b>Loaded: </b>' + layerName;
addShapefileToMap(response.featureCollection);
}),
error: lang.hitch(this, errorHandler)
});
}
function errorHandler (error) {
dom.byId('upload-status').innerHTML =
"<p style='color:red'>" + error.message + "</p>";
}
function addShapefileToMap (featureCollection) {
//add the shapefile to the map and zoom to the feature collection extent
//If you want to persist the feature collection when you reload browser you could store the collection in
//local storage by serializing the layer using featureLayer.toJson() see the 'Feature Collection in Local Storage' sample
//for an example of how to work with local storage.
var fullExtent;
var layers = [];
arrayUtils.forEach(featureCollection.layers, function (layer) {
var infoTemplate = new InfoTemplate("Details", "${*}");
var featureLayer = new FeatureLayer(layer, {
infoTemplate: infoTemplate
});
//associate the feature with the popup on click to enable highlight and zoom to
featureLayer.on('click', function (event) {
map.infoWindow.setFeatures([event.graphic]);
});
//change default symbol if desired. Comment this out and the layer will draw with the default symbology
changeRenderer(featureLayer);
fullExtent = fullExtent ?
fullExtent.union(featureLayer.fullExtent) : featureLayer.fullExtent;
layers.push(featureLayer);
});
map.addLayers(layers);
map.setExtent(fullExtent.expand(1.25), true);
dom.byId('upload-status').innerHTML = "";
}
function changeRenderer (layer) {
//change the default symbol for the feature collection for polygons and points
var symbol = null;
switch (layer.geometryType) {
case 'esriGeometryPoint':
symbol = new PictureMarkerSymbol({
'angle': 0,
'xoffset': 0,
'yoffset': 0,
'type': 'esriPMS',
'url': 'https://static.arcgis.com/images/Symbols/Shapes/BluePin1LargeB.png',
'contentType': 'image/png',
'width': 20,
'height': 20
});
break;
case 'esriGeometryPolygon':
symbol = new SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID,
new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID,
new Color([112, 112, 112]), 1), new Color([136, 136, 136, 0.25]));
break;
}
if (symbol) {
layer.setRenderer(new SimpleRenderer(symbol));
}
}
});
</script>
<body class="claro">
<div id="mainWindow" data-dojo-type="dijit/layout/BorderContainer" data-dojo-props="design:'headline',gutters:false" style="width:100%; height:100%;">
<div data-dojo-type="dijit/layout/ContentPane" id="rightPane" data-dojo-props="region:'right'">
<div style='padding-left:4px;'>
<p>
Add a zipped shapefile to the map.</p><p>Visit the
<a target='_blank' href="https://doc.arcgis.com/en/arcgis-online/reference/shapefiles.htm">Shapefiles</a> help topic for information and limitations.</p>
<form enctype="multipart/form-data" method="post" id="uploadForm">
<div class="field">
<label class="file-upload">
<span><strong>Add File</strong></span>
<input type="file" name="file" id="inFile" />
</label>
</div>
</form>
<span class="file-upload-status" style="opacity:1;" id="upload-status"></span>
<div id="fileInfo"> </div>
</div>
</div>
<div id="mapCanvas" data-dojo-type="dijit/layout/ContentPane" data-dojo-props="region:'center'"></div>
</div>
</body>
Updated JSFiddle Link-https://jsfiddle.net/vikash2402/Lrsrdojh/2/
I tried with with following Shapefile-
Source:- https://developers.arcgis.com/javascript/3/sandbox/sandbox.html?sample=portal_addshapefile
Hoping this will finally solve your issue!

For Loop - Changing src every loop

I'm trying to load pdfs and render every single page into a canvas.
It works when I'm only loading a one paged .pdf but not when I'm using a multiple page .pdf
The for-loop is supposed to run as often as there are pages in the pdf,
var total =
Every loop I'm creating a
<canvas class=''></canvas>
which should have the matching page number as class.
can.className = 'pdfpage' + i
But for some reason it always gets the total page count as class. E.g. when loading a five paged .pdf it creates...
<canvas class='pdfpage5'></canvas>
...5 times and not 'pdfpage0', 'pdfpage1', etc.
I'm pretty new to JS so I'm not exactly sure if I'm thinking in the right direction with 'i'. I added
console.log('i is: ' + i);
to confirm that i really adds +1 every turn.
<script src="http://cdnjs.cloudflare.com/ajax/libs/processing.js/1.4.1/processing-api.min.js"></script>
<script src="http://html2canvas.hertzen.com/build/html2canvas.js"></script>
<script type="text/javascript" src="https://rawgithub.com/mozilla/pdf.js/gh-pages/build/pdf.js"></script>
<script type="text/javascript" src='./jsPDF/jspdf.js'></script>
<script src="./jsPDF/plugins/addimage.js"></script>
<script src="./jsPDF/plugins/png_support.js"></script>
<script src="./jsPDF/plugins/canvas.js"></script>
<script type="text/javascript" src='./FileSaver.js-master/FileSaver.js'></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="https://rawgithub.com/mozilla/pdf.js/gh-pages/build/pdf.js"></script>
<div id='1'>
<input id='pdf' type='file'/>
<script type="text/javascript">
PDFJS.disableWorker = true;
var pdf = document.getElementById('pdf');
pdf.onchange = function(ev) {
if (file = document.getElementById('pdf').files[0]) {
fileReader = new FileReader();
fileReader.onload = function(ev) {
console.log(ev);
PDFJS.getDocument(fileReader.result).then(function getPdfHelloWorld(pdf) {
var total = pdf.numPages;
for (var i = 0; i < total; i++) {
console.log('i is: ' + i);
console.log('total pages: ' + total);
//
// Fetch the first page
//
console.log(pdf)
pdf.getPage(i + 1).then(function getPageHelloWorld(page) {
var scale = 1.0;
var viewport = page.getViewport(scale);
//
// Prepare canvas using PDF page dimensions
//
var div = document.getElementById('1');
var can = document.createElement('canvas');
can.className = 'pdfpage' +i;
div.appendChild(can);
canvas = document.getElementsByClassName('pdfpage' +i);
var context = canvas[0].getContext('2d');
canvas[0].height = viewport.height;
canvas[0].width = viewport.width;
//
// Render PDF page into canvas context
//
var task = page.render({canvasContext: context, viewport: viewport})
task.promise.then(function(){
console.log(canvas[0].toDataURL('image/jpeg'));
var dataURL = canvas[0].toDataURL('image/jpeg');
});
});
}
}, function(error){
console.log(error);
});
};
fileReader.readAsArrayBuffer(file);
}
}
</script>
</div>
Try this, it should add the required the classnames
<script src="http://cdnjs.cloudflare.com/ajax/libs/processing.js/1.4.1/processing-api.min.js"></script>
<script src="http://html2canvas.hertzen.com/build/html2canvas.js"></script>
<script type="text/javascript" src="https://rawgithub.com/mozilla/pdf.js/gh-pages/build/pdf.js"></script>
<script type="text/javascript" src='./jsPDF/jspdf.js'></script>
<script src="./jsPDF/plugins/addimage.js"></script>
<script src="./jsPDF/plugins/png_support.js"></script>
<script src="./jsPDF/plugins/canvas.js"></script>
<script type="text/javascript" src='./FileSaver.js-master/FileSaver.js'></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="https://rawgithub.com/mozilla/pdf.js/gh-pages/build/pdf.js"></script>
<div id='1'>
<input id='pdf' type='file'/>
<script type="text/javascript">
PDFJS.disableWorker = true;
var pdf = document.getElementById('pdf');
pdf.onchange = function(ev) {
if (file = document.getElementById('pdf').files[0]) {
fileReader = new FileReader();
fileReader.onload = function(ev) {
console.log(ev);
PDFJS.getDocument(fileReader.result).then(function getPdfHelloWorld(pdf) {
var total = pdf.numPages;
for (var i = 0; i < total; i++) {
console.log('i is: ' + i);
console.log('total pages: ' + total);
//
// Fetch the first page
//
console.log(pdf)
pdf.getPage(i + 1).then(function getPageHelloWorld(page) {
var scale = 1.0;
var viewport = page.getViewport(scale);
//
// Prepare canvas using PDF page dimensions
//
var div = document.getElementById('1');
var can = document.createElement('canvas');
can.className = 'pdfpage' +(page.pageIndex + 1);
div.appendChild(can);
canvas = document.getElementsByClassName('pdfpage' +(page.pageIndex + 1));
var context = canvas[0].getContext('2d');
canvas[0].height = viewport.height;
canvas[0].width = viewport.width;
//
// Render PDF page into canvas context
//
var task = page.render({canvasContext: context, viewport: viewport})
task.promise.then(function(){
console.log(canvas[0].toDataURL('image/jpeg'));
var dataURL = canvas[0].toDataURL('image/jpeg');
});
});
}
}, function(error){
console.log(error);
});
};
fileReader.readAsArrayBuffer(file);
}
}
</script>
</div>
Basically, all I have done is replace i with page.pageIndex +1 in the callback function

How to get image width and height using JavaScript before upload?

How to get image width and height using Javascript before upload? I tried to test my code, but it does not work. How can I achieve this?
https://jsfiddle.net/r78qkjba/1/
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input name="offer_image_1" onchange="check_thumbnail_image_format_fn()" type="file" id="offer_image_1" />
<script>
function check_thumbnail_image_format_fn() {
var offer_image_1_data = document.getElementById("offer_image_1");
var offer_image_1_data_file = offer_image_1_data.files[0];
var offer_image_1_data_file_width = offer_image_1_data_file.width;
var offer_image_1_data_file_height = offer_image_1_data_file.height;
alert(offer_image_1_data_file_width);
alert(offer_image_1_data_file_height);
};
</script>
HTML5 and the File API
Here's the uncommented working code snippet example:
window.URL = window.URL || window.webkitURL;
var elBrowse = document.getElementById("browse"),
elPreview = document.getElementById("preview"),
useBlob = false && window.URL; // `true` to use Blob instead of Data-URL
function readImage (file) {
var reader = new FileReader();
reader.addEventListener("load", function () {
var image = new Image();
image.addEventListener("load", function () {
var imageInfo = file.name +' '+
image.width +'×'+
image.height +' '+
file.type +' '+
Math.round(file.size/1024) +'KB';
elPreview.appendChild( this );
elPreview.insertAdjacentHTML("beforeend", imageInfo +'<br>');
});
image.src = useBlob ? window.URL.createObjectURL(file) : reader.result;
if (useBlob) {
window.URL.revokeObjectURL(file); // Free memory
}
});
reader.readAsDataURL(file);
}
elBrowse.addEventListener("change", function() {
var files = this.files;
var errors = "";
if (!files) {
errors += "File upload not supported by your browser.";
}
if (files && files[0]) {
for(var i=0; i<files.length; i++) {
var file = files[i];
if ( (/\.(png|jpeg|jpg|gif)$/i).test(file.name) ) {
readImage( file );
} else {
errors += file.name +" Unsupported Image extension\n";
}
}
}
if (errors) {
alert(errors);
}
});
#preview img{height:100px;}
<input id="browse" type="file" multiple />
<div id="preview"></div>
Using an input and a div for the images preview area
<input id="browse" type="file" multiple>
<div id="preview"></div>
let's also use a CSS to keep the resulting images a reasonable height:
#preview img{ height:100px; }
JavaScript:
window.URL = window.URL || window.webkitURL;
var elBrowse = document.getElementById("browse"),
elPreview = document.getElementById("preview"),
useBlob = false && window.URL; // `true` to use Blob instead of Data-URL
// 2.
function readImage (file) {
// 2.1
// Create a new FileReader instance
// https://developer.mozilla.org/en/docs/Web/API/FileReader
var reader = new FileReader();
// 2.3
// Once a file is successfully readed:
reader.addEventListener("load", function () {
// At this point `reader.result` contains already the Base64 Data-URL
// and we've could immediately show an image using
// `elPreview.insertAdjacentHTML("beforeend", "<img src='"+ reader.result +"'>");`
// But we want to get that image's width and height px values!
// Since the File Object does not hold the size of an image
// we need to create a new image and assign it's src, so when
// the image is loaded we can calculate it's width and height:
var image = new Image();
image.addEventListener("load", function () {
// Concatenate our HTML image info
var imageInfo = file.name +' '+ // get the value of `name` from the `file` Obj
image.width +'×'+ // But get the width from our `image`
image.height +' '+
file.type +' '+
Math.round(file.size/1024) +'KB';
// Finally append our created image and the HTML info string to our `#preview`
elPreview.appendChild( this );
elPreview.insertAdjacentHTML("beforeend", imageInfo +'<br>');
});
image.src = useBlob ? window.URL.createObjectURL(file) : reader.result;
// If we set the variable `useBlob` to true:
// (Data-URLs can end up being really large
// `src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAA...........etc`
// Blobs are usually faster and the image src will hold a shorter blob name
// src="blob:http%3A//example.com/2a303acf-c34c-4d0a-85d4-2136eef7d723"
if (useBlob) {
// Free some memory for optimal performance
window.URL.revokeObjectURL(file);
}
});
// 2.2
// https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL
reader.readAsDataURL(file);
}
// 1.
// Once the user selects all the files to upload
// that will trigger a `change` event on the `#browse` input
elBrowse.addEventListener("change", function() {
// Let's store the FileList Array into a variable:
// https://developer.mozilla.org/en-US/docs/Web/API/FileList
var files = this.files;
// Let's create an empty `errors` String to collect eventual errors into:
var errors = "";
if (!files) {
errors += "File upload not supported by your browser.";
}
// Check for `files` (FileList) support and if contains at least one file:
if (files && files[0]) {
// Iterate over every File object in the FileList array
for(var i=0; i<files.length; i++) {
// Let's refer to the current File as a `file` variable
// https://developer.mozilla.org/en-US/docs/Web/API/File
var file = files[i];
// Test the `file.name` for a valid image extension:
// (pipe `|` delimit more image extensions)
// The regex can also be expressed like: /\.(png|jpe?g|gif)$/i
if ( (/\.(png|jpeg|jpg|gif)$/i).test(file.name) ) {
// SUCCESS! It's an image!
// Send our image `file` to our `readImage` function!
readImage( file );
} else {
errors += file.name +" Unsupported Image extension\n";
}
}
}
// Notify the user for any errors (i.e: try uploading a .txt file)
if (errors) {
alert(errors);
}
});
Hope below code will help you.
var _URL = window.URL || window.webkitURL;
$("#offer_image_1").change(function (e) {
var file, img;
if ((file = this.files[0])) {
img = new Image();
img.onload = function () {
alert(this.width + " " + this.height);
};
img.src = _URL.createObjectURL(file);
}
});
You don't need to add onchange event at the input node.
This code is taken from
Check image width and height before upload with Javascript

Phonegap photo upload script error

Trying to upload a photo from my phone to a remote server using phonegap. After compiling when I run the app I got an error message:
Upload failed code = 3.
I read the web and found out there should be an added line of script which I added (
options.chunkedMode = false;
options.headers = {
Connection: "close"
)
Still gets the same error again.
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no;" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>PhoneGap</title>
<style type="text/css">
div {border: 1px solid black;}
input {width: 100%;}
</style>
<script src="cordova-2.5.0.js"></script>
<script type="text/javascript" charset="utf-8">
var deviceReady = false;
/**
* Take picture with camera
*/
function takePicture() {
navigator.camera.getPicture(
function(uri) {
var img = document.getElementById('camera_image');
img.style.visibility = "visible";
img.style.display = "block";
img.src = uri;
document.getElementById('camera_status').innerHTML = "Success";
},
function(e) {
console.log("Error getting picture: " + e);
document.getElementById('camera_status').innerHTML = "Error getting picture.";
},
{ quality: 50, destinationType: navigator.camera.DestinationType.FILE_URI});
};
/**
* Select picture from library
*/
function selectPicture() {
navigator.camera.getPicture(
function(uri) {
var img = document.getElementById('camera_image');
img.style.visibility = "visible";
img.style.display = "block";
img.src = uri;
document.getElementById('camera_status').innerHTML = "Success";
},
function(e) {
console.log("Error getting picture: " + e);
document.getElementById('camera_status').innerHTML = "Error getting picture.";
},
{ quality: 50, destinationType: navigator.camera.DestinationType.FILE_URI, sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY});
};
/**
* Upload current picture
*/
function uploadPicture() {
// Get URI of picture to upload
var img = document.getElementById('camera_image');
var imageURI = img.src;
if (!imageURI || (img.style.display == "none")) {
document.getElementById('camera_status').innerHTML = "Take picture or select picture from library first.";
return;
}
// Verify server has been entered
server = document.getElementById('serverUrl').value;
if (server) {
// Specify transfer options
var options = new FileUploadOptions();
options.fileKey="file";
options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
options.mimeType="image/jpeg";
options.chunkedMode = false;
options.headers = {
Connection: "close"
}
options.chunkedMode = false;
// Transfer picture to server
var ft = new FileTransfer();
ft.upload(imageURI, 'http://mywebsite/upload.php', function(r) {
document.getElementById('camera_status').innerHTML = "Upload successful: "+r.bytesSent+" bytes uploaded.";
}, function(error) {
document.getElementById('camera_status').innerHTML = "Upload failed: Code = "+error.code;
}, options);
}
}
/**
* View pictures uploaded to the server
*/
function viewUploadedPictures() {
// Get server URL
server = document.getElementById('serverUrl').value;
if (server) {
// Get HTML that lists all pictures on server using XHR
var xmlhttp = new XMLHttpRequest();
// Callback function when XMLHttpRequest is ready
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState === 4){
// HTML is returned, which has pictures to display
if (xmlhttp.status === 200) {
document.getElementById('server_images').innerHTML = xmlhttp.responseText;
}
// If error
else {
document.getElementById('server_images').innerHTML = "Error retrieving pictures from server.";
}
}
};
xmlhttp.open("GET", server , true);
xmlhttp.send();
}
}
/**
* Function called when page has finished loading.
*/
function init() {
document.addEventListener("deviceready", function() {deviceReady = true;}, false);
window.setTimeout(function() {
if (!deviceReady) {
alert("Error: PhoneGap did not initialize. Demo will not run correctly.");
}
},2000);
}
</script>
</head>
<body onload="init();">
<h3>PhoneGap Camera Upload Demo</h3>
<div>
<h3>Server URL for upload.php:</h3>
<input id="serverUrl" type="text" value="http://mywebsite/pictures.php" />
</div>
<br/>
<!-- Camera -->
<div>
<h3>Camera:</h3>
<b>Status:</b> <span id="camera_status"></span><br>
<b>Image:</b> <img style="width:120px;visibility:hidden;display:none;" id="camera_image" src="" />
</div>
<!-- Actions -->
<div>
<input type="button" onclick="takePicture();" value="Take Picture" /><br/>
<input type="button" onclick="selectPicture();" value="Select Picture from Library" /><br/>
<input type="button" onclick="uploadPicture();" value="Upload Picture" />
</div>
<br/>
<!-- Server pictures -->
<div>
<h3>Server:</h3>
<b>Images on server:</b>
<div id="server_images"></div>
</div>
<!-- Actions -->
<div>
<input type="button" onclick="viewUploadedPictures();" value="View Uploaded Pictures" />
</div>
</body>
</html>
Make sure your upload function is similar like this
function upload() {
var img = document.getElementById('image');
var imageURI = img.src;
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = imageURI.substr(imageURI.lastIndexOf('/') + 1);
options.mimeType = "image/jpeg";
var params = new Object();
options.params = params;
options.chunkedMode = false;
var ft = new FileTransfer();
ft.upload(imageURI, "https://www.example.com/upload.php", win, fail,
options);
}
It's working 100%.
Reference: http://blog.revivalx.com/2014/07/12/upload-image-using-file-transfer-cordova-plugin-for-ios-and-android/

Categories

Resources