Phonegap photo upload script error - javascript

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/

Related

Image from canvas is not saved correctly

Good day to all users!
I have a problem that my screenshots rendered on canvas are not saved correctly.
Displaying screenshot on canvas using js
function retrieveImageFromClipboardAsBlob(pasteEvent, callback){
if(pasteEvent.clipboardData == false){
if(typeof(callback) == "function"){
callback(undefined);
}
};
var items = pasteEvent.clipboardData.items;
if(items == undefined){
if(typeof(callback) == "function"){
callback(undefined);
}
};
for (var i = 0; i < items.length; i++) {
if (items[i].type.indexOf("image") == -1) continue;
var blob = items[i].getAsFile();
if(typeof(callback) == "function"){
callback(blob);
}
}
}
window.addEventListener("paste", function(e){
retrieveImageFromClipboardAsBlob(e, function(imageBlob){
if(imageBlob){
var canvas = document.getElementById("mycanvas");
var ctx = canvas.getContext('2d');
var img = new Image();
img.onload = function(){
canvas.width = this.width;
canvas.height = this.height;
ctx.drawImage(img, 0, 0);
};
var URLObj = window.URL || window.webkitURL;
img.src = URLObj.createObjectURL(imageBlob);
}
});
var cnv = document.getElementById("mycanvas");
var sendCanvas = function (cnv) {
var imgs = cnv.toDataURL('image/png').replace('data:image/png;base64,','');
var sender = new XMLHttpRequest();
sender.open('POST', '/temp.php', true);
sender.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
sender.onreadystatechange = function () {
if (sender.readyState == 4) {}
};
sender.send('imgs='+imgs);
};
sendCanvas(cnv);
}, false);
First, the screenshot is drawn on canvas and then sent to the php handler.
My html form has:
<canvas id="mycanvas">
<?php
$imgs = str_replace(' ', '+', $_POST['imgs']);
$imgs = base64_decode($imgs);
$shootname = "screenshot".rand().".png";
$screendir = "/mnt/ElmaFiles/".$shootname;
file_put_contents($screendir, $imgs);
$screennames .= $shootname.",";
?>
<p><input type="submit" name="submit1" class="btn success"></p>
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"</script>
<script src="/script11.js"></script>
In my understanding, files should be saved to the specified folder when I press ctrl + v. But it doesn't really work like that.
For example, I transfer 3 screenshots, but 5 screenshots are saved in my folder:
Please help me understand where is my mistake?
Thank you very much in advance!
I forgot to add: when 5 screenshots were saved, only the third and fourth could be opened from them, and the rest wrote an error like "incorrect format"
I did a little rewrite of the above which I hope will help solve some of the issues you were having.
The PHP that saves the image to disk should be explicitly targeted so that trying to call $_POST['imgs'] for a regular GET request will not cause issue. For sending the binary data to the server rather than XMLHttpRequest instead use fetch ~ a considerably more powerful api.
<?php
error_reporting( E_ALL );
ini_set( 'display_errors', 1 );
if( $_SERVER['REQUEST_METHOD']=='POST' && !empty( $_POST['imgs'] ) ){
ob_clean();
$decoded=base64_decode( $_POST['imgs'] );
#edit directory to suit. This is a sub-folder to where the script is currently running.
$dir=sprintf('%s/images/tmp',__DIR__);
$filename=sprintf('screenshot%s.png', rand() );
$targetfile=sprintf('%s%s%s', realpath($dir), DIRECTORY_SEPARATOR, $filename );
file_put_contents( $targetfile, $decoded );
exit( $filename );
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title></title>
<script>
document.addEventListener('DOMContentLoaded',()=>{
function getBlob(evt,callback){
if( evt.clipboardData == false || evt.clipboardData.items=='undefined' ){
return false;
};
let items = evt.clipboardData.items;
for( let i=0; i < items.length; i++){
let item=items[i];
if( ~item.type.indexOf('image') )callback( item.getAsFile() );
}
}
window.addEventListener('paste', function(e){
let canvas = document.querySelector('canvas');
let ctxt = canvas.getContext('2d');
const callback=function( blob ){
if( blob ){
let img = new Image();
img.onload = function(){
canvas.width=this.width;
canvas.height=this.height;
ctxt.drawImage( img, 0, 0 );
};
img.src = URL.createObjectURL(blob);
return true;
}
return false;
};
getBlob( e, callback );
let fd=new FormData();
fd.append('imgs', canvas.toDataURL('image/png').replace('data:image/png;base64,',''));
fetch( location.href,{ method:'post', body:fd })
.then( r=>r.text() )
.then( text=>{
console.info('Screenshot %s saved',text )
})
});
});
</script>
</head>
<body>
<canvas></canvas>
</body>
</html>

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>

Limit amount of uploaded Images [duplicate]

This question already has answers here:
How can restrict user to upload max 10 files at once?
(2 answers)
Closed 2 years ago.
I have this JavaScript code which lets users upload and preview their uploaded images.
The images are being previewed through a table grid with specified dimensions.
My Question:
How can I edit the JavaScript to limit users from uploading more than 9 images?
Note: the same restriction would be implemented on the server side later on. Due to users being able to bypass this JavaScript code. But that's for later. For now I want to get the frontend to limit the users.
Note: This question has been asked before but was based solely on limiting file input button. My problem is implementing this code with mine.
Code in question (to limit file upload)
$(function() {
$("button[type = 'submit']").click(function(event) {
var $fileUpload = $("input[type='file']");
if (parseInt($fileUpload.get(0).files.length) > 10) {
alert("You are only allowed to upload a maximum of 10 files");
event.preventDefault();
}
});
});
(function (global) {
var imagesPerRow = 3,
chooseFiles,
columns,
previews;
function PreviewImages() {
var row;
Array.prototype.forEach.call(chooseFiles.files, function (file, index) {
var cindex = index % imagesPerRow,
oFReader = new FileReader(),
cell,
image;
if (cindex === 0) {
row = previews.insertRow(Math.ceil(index / imagesPerRow));
}
image = document.createElement("img");
image.id = "img_" + index;
image.style.objectFit = "cover";
image.style.width = "150px";
image.style.height = "90px";
cell = row.insertCell(cindex);
cell.appendChild(image);
oFReader.addEventListener("load", function assignImageSrc(evt) {
image.src = evt.target.result;
this.removeEventListener("load", assignImageSrc);
}, false);
oFReader.readAsDataURL(file);
});
}
global.addEventListener("load", function windowLoadHandler() {
global.removeEventListener("load", windowLoadHandler);
chooseFiles = document.getElementById("chooseFiles");
columns = document.getElementById("columns");
previews = document.getElementById("previews");
var row = columns.insertRow(-1),
header,
i;
for (i = 0; i < imagesPerRow; i += 1) {
header = row.insertCell(-1);
header.style.width = (100 / imagesPerRow) + "%";
}
chooseFiles.addEventListener("change", PreviewImages, false);
}, false);
}(window));
div.rounded {
width: 100%;
border-style: solid;
border-width: 1px;
border-radius: 5px;
}
label {
display: block;
}
input {
display: block;
}
#previewTable {
width: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<div id="imagesDiv" class="rounded">
<label for="chooseFiles">Add Images</label>
<input type="file" id="chooseFiles" multiple="multiple" />
<table id="previewTable">
<thead id="columns"></thead>
<tbody id="previews"></tbody>
</table>
</div>
You can modify your javascript code to check the files.length property of the input type="file" element & set the files array empty by assigning the value property of the input element to an empty string if the files.length is more than 9.
check the modified javascript code:
(function (global) {
var imagesPerRow = 3,
chooseFiles,
columns,
previews;
global.addEventListener("load", function windowLoadHandler() {
global.removeEventListener("load", windowLoadHandler);
chooseFiles = document.getElementById("chooseFiles");
columns = document.getElementById("columns");
previews = document.getElementById("previews");
var row = columns.insertRow(-1),
header,
i;
for (i = 0; i < imagesPerRow; i += 1) {
header = row.insertCell(-1);
header.style.width = (100 / imagesPerRow) + "%";
}
chooseFiles.addEventListener("change", function (e) {
if(this.files.length > 9){
alert("You are only allowed to upload a maximum of 9 files");
this.value = "";
e.preventDefault();
}
else{
var row;
Array.prototype.forEach.call(chooseFiles.files, function (file, index) {
var cindex = index % imagesPerRow,
oFReader = new FileReader(),
cell,
image;
if (cindex === 0) {
row = previews.insertRow(Math.ceil(index / imagesPerRow));
}
image = document.createElement("img");
image.id = "img_" + index;
image.style.objectFit = "cover";
image.style.width = "150px";
image.style.height = "90px";
cell = row.insertCell(cindex);
cell.appendChild(image);
oFReader.addEventListener("load", function assignImageSrc(evt) {
image.src = evt.target.result;
this.removeEventListener("load", assignImageSrc);
}, false);
oFReader.readAsDataURL(file);
});
}
}, false);
}, false);
}(window));
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Responsive</title>
<link rel="stylesheet" href="./assets/css/custom.css">
</head>
<body>
<div id="imagesDiv" class="rounded">
<label for="chooseFiles">Add Images</label>
<input type="file" id="chooseFiles" multiple="multiple" />
<table id="previewTable">
<thead id="columns"></thead>
<tbody id="previews"></tbody>
</table>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="./assets/js/main.js"></script>
</body>
</html>
Hope this solves your problem.
I can't really understand the code displayed above, but what you can do is:
Define variable uploadedImages = 0 so that every time the user uploads a photo on the website, uploadedImages increments by one. Also, make an IF statement that checks every time before uploading a photo, and only upload the image if the uploadedImages didn't pass the max number of uploaded images allowed.
I tried to implement this in your code but I can't figure out how it works.

how to make javascript validate image before upload image, with prevent the preview image

I have a function to upload an image with FileReader method, if the file image was choose it will showing as a preview image before i upload it, i want to make some validation to read the image width, if it false the preview image should not appear, i'm confused how to make it, since i can not place the file reader inside the image.load scoope: here is my code below :
var input = document.getElementById('fileTrigger');
var el = document.createElement('IMG');
input.addEventListener('change', function({target}){
var file = target.files[0];
var reader = new FileReader();
var image = new Image();
reader.onload = function(e){
if(file) {
image.onload = function(e){
var width = e.target.width;
console.log(width);
if(width !== 100){
console.log('fail')
}
}
image.src = reader.result;
}
el.src = e.target.result;
document.body.appendChild(el)
}
reader.readAsDataURL(file);
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title></title>
</head>
<body>
<input type="file" id="fileTrigger">
</body>
</html>
var input = document.getElementById('fileTrigger');
var el = document.createElement('IMG');
var elResult
input.addEventListener('change', function({target}){
el.src=""
var file = target.files[0];
var reader = new FileReader();
var image = new Image();
reader.onload = function(e){
elResult=e.target.result;
if(file) {
image.onload = function(e){
var width = e.target.width;
console.log(width);
if(width >=300){
console.log('fail')
}else{
el.src = elResult
document.body.appendChild(el)
}
}
image.src = reader.result;
}
}
reader.readAsDataURL(file);
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title></title>
</head>
<body>
<input type="file" id="fileTrigger">
</body>
</html>
Hope this will helps you..:)

Image previewing before upload in phonegap

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>

Categories

Resources