HTML5 file api and octokit.js and binary file - javascript

I try to make form which can upload binary data via octokit.js to the github. For example some pdf or image (binary blob). My problem is that all my attempts ends with damaged data at the github side.
Minimal working example: http://jsfiddle.net/keddie/7r3f4q77/
var _arrayBufferToBase64 = function (buffer) {
var binary = '';
var bytes = new Uint8Array(buffer);
var len = bytes.byteLength;
for (var i = 0; i < len; i++) {
binary += String.fromCharCode(bytes[i]);
}
return window.btoa(binary);
};
var go = function () {
var config = {
user: $('#user').val(),
repo: $('#repo').val(),
token: $('#token').val(),
handler: document.getElementById('file').files[0]
};
var reader = new FileReader();
var github = new Octokit({
token: config.token
});
var repo = github.getRepo(config.user, config.repo);
var branch = repo.getBranch();
reader.onloadend = function (evt) {
var files = {};
if (evt.target.readyState == FileReader.DONE) {
/* Anothers attempts:
files[ 'x1.pdf' ] = {
isBase64: true,
content: evt.target.result
};
files[ 'x2.pdf' ] = {
isBase64: true,
content: evt.target.result.substring('data:application/octet-stream;base64,'.length)
};
*/
files['x4.pdf'] = {
isBinary: true,
isBase64: true,
content: _arrayBufferToBase64(evt.target.result)
};
} else {
console.warn(evt.target.error);
}
branch.writeMany(files, "API test commit 1").then(function (res) {
if (res) {
console.log('ok');
$('#result').text('OK');
} else {
console.error(res);
$('#result').text('Error');
}
});
};
var blob = config.handler.slice(0, config.handler.size);
//reader.readAsDataURL(blob);
reader.readAsArrayBuffer(blob);
};
$(document).ready(function () {
$('#submit').click(go);
});
And HTML:
<p>User:
<input type="text" id="user" />
</p>
<p>Repo:
<input type="text" id="repo" />
</p>
<p>Token:
<input type="text" id="token" />
</p>
<p>File:
<input type="file" id="file" />
</p>
<p>
<button id="submit">Submit</button>
</p>
<p id="result"></p>
My second problem is how to find filename in reader.onloadend callback (but this is minor issue).
Relevant is this issue: https://github.com/philschatz/octokit.js/issues/44

Problem was in octokit.js library.
I prepare pull request: https://github.com/philschatz/octokit.js/pull/72

Related

when pushing multiple files into array as base64 it gives DOMException: An attempt was made to use an object that is not, or is no longer, usable

I'm working on a vue.js application and i'm adding multiple file uploader with slide option. I'm using below method
<input
id="file-upload"
ref="file"
class="custom-file-input"
multiple
name="document_file"
type="file"
#change="setFile($event)"
/>
<label class="custom-file-label selected overflow-hide">{{ $t('Browse') }}</label>
data() {
return {
imageUrls: [],
img_id: 0,
currentIndex: 0
}
},
setFile(e) {
let self = this;
let reader = new FileReader();
if(e.target.files.length > 0){
for (let i = 0; i < e.target.files.length; i++) {
alert();
reader.readAsDataURL(e.target.files[i]);
reader.onload = function () {
self.imageUrls.push(
{
id: self.img_id,
file: reader.result
});
self.img_id++;
}
}
console.log('imageUrls: ', self.imageUrls);
}
},
with the alert object(all the selected files) are being pushed to array. but when i comment the alert it's giving below error
DOMException: An attempt was made to use an object that is not, or is no longer, usable
what is the reason for this?
You have to use FileReader() object for each files. try this
<input
id="file-upload"
ref="file"
class="custom-file-input"
multiple
name="document_file"
type="file"
#change="setFile"
/>
<label class="custom-file-label selected overflow-hide">{{ $t('Browse') }}</label>
data() {
return {
images: [],
imageUrls: [],
img_id: 0,
currentIndex: 0
}
},
setFile(e) {
let self = this;
var selectedFiles = e.target.files;
//let reader = new FileReader();
for (let i = 0; i < selectedFiles.length; i++) {
console.log(selectedFiles[i]);
this.images.push(selectedFiles[i]);
}
for (let i = 0; i < this.images.length; i++) {
let reader = new FileReader();
reader.onload = (e) => {
//this.$refs.image[i].src = reader.result;
// console.log(reader.result);
self.imageUrls.push(
{
id: self.img_id,
file: reader.result
});
self.img_id++;
//console.log(this.$refs.image[i].src);
};
reader.readAsDataURL(this.images[i]);
}
console.log('imageUrls: ', self.imageUrls);
},
using let reader = new FileReader(); inside the loop solve the problem
setFile(e) {
let self = this;
for (let i = 0; i < e.target.files.length; i++) {
let reader = new FileReader();
reader.readAsDataURL(e.target.files[i]);
reader.onload = function () {
self.imageUrls.push({
id: self.img_id,
file: reader.result,
});
self.img_id++;
};
}
console.log(self.imageUrls);
},

How to access to specific row of excel file using Javascript

I am reading random row of large Excel file using Javascript. But it is taking some time for example when I am working with 300.000 row data in excel file. I need fast way.
<body>
<input type="file" id="fileUpload" />
<input type="button" id="upload" value="Upload" onclick="Upload()" />
<!-- <input type="button" id="upload" value="Random" onclick="ProcessExcel()" /> -->
<hr />
<h1 id="exc">Hello</h1>
<p id="her"></p>
<p id="limm"></p>
<div id="dvExcel"></div>
<script type="text/javascript">
// var gl_ex = "";
function Upload() {
//Reference the FileUpload element.
var fileUpload = document.getElementById("fileUpload");
//Validate whether File is valid Excel file.
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.xls|.xlsx)$/;
if (regex.test(fileUpload.value.toLowerCase())) {
if (typeof (FileReader) != "undefined") {
var reader = new FileReader();
//For Browsers other than IE.
if (reader.readAsBinaryString) {
reader.onload = function (e) {
ProcessExcel(e.target.result);
};
reader.readAsBinaryString(fileUpload.files[0]);
} else {
//For IE Browser.
reader.onload = function (e) {
var data = "";
var bytes = new Uint8Array(e.target.result);
for (var i = 0; i < bytes.byteLength; i++) {
data += String.fromCharCode(bytes[i]);
}
ProcessExcel(data);
// gl_ex = data;
//alert("Uploaded.");
};
reader.readAsArrayBuffer(fileUpload.files[0]);
}
} else {
alert("This browser does not support HTML5.");
}
} else {
alert("Please upload a valid Excel file.");
}
};
function ProcessExcel(data) {
//var data = "";
//data = gl_ex;
//Read the Excel File data.
var workbook = XLSX.read(data, {
type: 'binary'
});
//Fetch the name of First Sheet.
var firstSheet = workbook.SheetNames[0];
//Read all rows from First Sheet into an JSON array.
var excelRows = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[firstSheet]);
var len = excelRows.length;
var rand_num = Math.floor((Math.random() * len) + 1);
document.getElementById("her").innerHTML = rand_num;
document.getElementById("limm").innerHTML = len;
document.getElementById("exc").innerHTML = excelRows[rand_num-1].Name;
};
</script>
</body>
As in example shown I am reading random row from Excel file. I think javascript is reading whole excel file sequentially. Can I read specific row data in faster way?

Preview images before upload

I have a page with four images for the user to select. I want the user to be able to preview each image on the site before upload.
The JavaScript code below works for only one image but I would like it to work for multiple images uploaded via <input type="file">.
What will be the best way to do this?
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#output').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#file-input").change(function () {
readURL(this);
});
Here is jQuery version for you. I think it more simplest thing.
$(function() {
// Multiple images preview in browser
var imagesPreview = function(input, placeToInsertImagePreview) {
if (input.files) {
var filesAmount = input.files.length;
for (i = 0; i < filesAmount; i++) {
var reader = new FileReader();
reader.onload = function(event) {
$($.parseHTML('<img>')).attr('src', event.target.result).appendTo(placeToInsertImagePreview);
}
reader.readAsDataURL(input.files[i]);
}
}
};
$('#gallery-photo-add').on('change', function() {
imagesPreview(this, 'div.gallery');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" multiple id="gallery-photo-add">
<div class="gallery"></div>
Add the multiple attribute to your HTMLInputElement
Add the accept attribute to your HTMLInputElement
To filter your files selection to images only, use accept="image/*", or a comma separated MIME list: accept="image/png, image/jpeg"
Use FileReader.readAsDataURL to get the Base64 string,
or URL.createObjectURL to get the file Blob object
Using FileReader.readAsDataURL
The asynchronous way to read the image data is by using FileReader API and its readAsDataURL method which returns a Base64 String:
const preview = (file) => {
const fr = new FileReader();
fr.onload = () => {
const img = document.createElement("img");
img.src = fr.result; // String Base64
img.alt = file.name;
document.querySelector('#preview').append(img);
};
fr.readAsDataURL(file);
};
document.querySelector("#files").addEventListener("change", (ev) => {
if (!ev.target.files) return; // Do nothing.
[...ev.target.files].forEach(preview);
});
#preview img { max-height: 100px; }
<input id="files" type="file" accept="image/*" multiple>
<div id="preview"></div>
Async strategy:
Due to the asynchronous nature of FileReader, you could implement an async/await strategy:
// DOM utility functions:
const el = (sel, par) => (par || document).querySelector(sel);
const elNew = (tag, props) => Object.assign(document.createElement(tag), props);
// Preview images before upload:
const elFiles = el("#files");
const elPreview = el("#preview");
const previewImage = (props) => elPreview.append(elNew("img", props));
const reader = (file, method = "readAsDataURL") => new Promise((resolve, reject) => {
const fr = new FileReader();
fr.onload = () => resolve({ file, result: fr.result });
fr.onerror = (err) => reject(err);
fr[method](file);
});
const previewImages = async(files) => {
// Remove existing preview images
elPreview.innerHTML = "";
let filesData = [];
try {
// Read all files. Return Array of Promises
const readerPromises = files.map((file) => reader(file));
filesData = await Promise.all(readerPromises);
} catch (err) {
// Notify the user that something went wrong.
elPreview.textContent = "An error occurred while loading images. Try again.";
// In this specific case Promise.all() might be preferred over
// Promise.allSettled(), since it isn't trivial to modify a FileList
// to a subset of files of what the user initially selected.
// Therefore, let's just stash the entire operation.
console.error(err);
return; // Exit function here.
}
// All OK. Preview images:
filesData.forEach(data => {
previewImage({
src: data.result, // Base64 String
alt: data.file.name // File.name String
});
});
};
elFiles.addEventListener("change", (ev) => {
if (!ev.currentTarget.files) return; // Do nothing.
previewImages([...ev.currentTarget.files]);
});
#preview img { max-height: 100px; }
<input id="files" type="file" accept="image/*" multiple>
<div id="preview"></div>
Using URL.createObjectURL
The synchronous way to read the image is by using the URL API and its createObjectURL method which returns a Blob:
const preview = (file) => {
const img = document.createElement("img");
img.src = URL.createObjectURL(file); // Object Blob
img.alt = file.name;
document.querySelector('#preview').append(img);
};
document.querySelector("#files").addEventListener("change", (ev) => {
if (!ev.target.files) return; // Do nothing.
[...ev.target.files].forEach(preview);
});
#preview img { max-height: 120px; }
<input id="files" type="file" accept="image/*" multiple>
<div id="preview"></div>
Although looks much simpler, it has implications on the main thread due to its synchronicity, and requires you to manually use (when possible) URL.revokeObjectURL in order to free up memory:
// Remove unused images from #preview? Consider also using
URL.revokeObjectURL(someImg.src); // Free up memory space
jQuery example:
A jQuery implementation of the above FileReader.readAsDataURL() example:
const preview = (file) => {
const fr = new FileReader();
fr.onload = (ev) => {
$('#preview').append($("<img>", {src: fr.result, alt: file.name}));
};
fr.readAsDataURL(file);
};
$("#files").on("change", (ev) => {
if (!ev.target.files) return; // Do nothing.
[...ev.target.files].forEach(preview);
});
#preview img { max-height: 120px; }
<input id="files" type="file" accept="image/*" multiple>
<div id="preview"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
Additional read:
File API — Using files from web applications (MDN)
readAsDataURL (MDN)
FileReader result (MDN)
Promise.all() (MDN)
Preview Image, get file size, image height and width before upload
Tips:
Besides using the HTMLInputElement attribute accept, if you want to make sure within JavaScript that a file is-of-type, you could:
if (!/\.(jpe?g|png|gif)$/i.test(file.name)) {
// Not a valid image
}
or like:
if (!/^image\//i.test(file.type)) {
// File is not of type Image
}
function previewMultiple(event){
var saida = document.getElementById("adicionafoto");
var quantos = saida.files.length;
for(i = 0; i < quantos; i++){
var urls = URL.createObjectURL(event.target.files[i]);
document.getElementById("galeria").innerHTML += '<img src="'+urls+'">';
}
}
#galeria{
display: flex;
}
#galeria img{
width: 85px;
height: 85px;
border-radius: 10px;
box-shadow: 0 0 8px rgba(0,0,0,0.2);
opacity: 85%;
}
<input type="file" multiple onchange="previewMultiple(event)" id="adicionafoto">
<div id="galeria">
</div>
Just use FileReader.readAsDataURL()
HTML:
<div id='photos-preview'></div>
<input type="file" id="fileupload" multiple (change)="handleFileInput($event.target.files)" />
JS:
function handleFileInput(fileList: FileList) {
const preview = document.getElementById('photos-preview');
Array.from(fileList).forEach((file: File) => {
const reader = new FileReader();
reader.onload = () => {
var image = new Image();
image.src = String(reader.result);
preview.appendChild(image);
}
reader.readAsDataURL(file);
});
}
DEMO
$(function() {
// Multiple images preview in browser
var imagesPreview = function(input, placeToInsertImagePreview) {
if (input.files) {
var filesAmount = input.files.length;
for (i = 0; i < filesAmount; i++) {
var reader = new FileReader();
reader.onload = function(event) {
$($.parseHTML('<img>')).attr('src', event.target.result).appendTo(placeToInsertImagePreview);
}
reader.readAsDataURL(input.files[i]);
}
}
};
$('#gallery-photo-add').on('change', function() {
imagesPreview(this, 'div.gallery');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" multiple id="gallery-photo-add">
<div class="gallery"></div>
function previewImages() {
var preview = document.querySelector('#preview');
if (this.files) {
[].forEach.call(this.files, readAndPreview);
}
function readAndPreview(file) {
// Make sure `file.name` matches our extensions criteria
if (!/\.(jpe?g|png|gif)$/i.test(file.name)) {
return alert(file.name + " is not an image");
} // else...
var reader = new FileReader();
reader.addEventListener("load", function() {
var image = new Image();
image.height = 100;
image.title = file.name;
image.src = this.result;
preview.appendChild(image);
});
reader.readAsDataURL(file);
}
}
document.querySelector('#file-input').addEventListener("change", previewImages);
<input id="file-input" type="file" multiple>
<div id="preview"></div>
function previewImages() {
var preview = document.querySelector('#preview');
if (this.files) {
[].forEach.call(this.files, readAndPreview);
}
function readAndPreview(file) {
// Make sure `file.name` matches our extensions criteria
if (!/\.(jpe?g|png|gif)$/i.test(file.name)) {
return alert(file.name + " is not an image");
} // else...
var reader = new FileReader();
reader.addEventListener("load", function() {
var image = new Image();
image.height = 100;
image.title = file.name;
image.src = this.result;
preview.appendChild(image);
});
reader.readAsDataURL(file);
}
}
document.querySelector('#file-input').addEventListener("change", previewImages);
<input id="file-input" type="file" multiple>
<div id="preview"></div>
<script type="text/javascript">
var upcontrol = {
queue : null, // upload queue
now : 0, // current file being uploaded
start : function (files) {
// upcontrol.start() : start upload queue
// WILL ONLY START IF NO EXISTING UPLOAD QUEUE
if (upcontrol.queue==null) {
// VISUAL - DISABLE UPLOAD UNTIL DONE
upcontrol.queue = files;
document.getElementById('uploader').classList.add('disabled');
// PREVIEW UPLOAD IMAGES
upcontrol.preview();*enter code here*
//PROCESS UPLOAD ON CLICK
$('#add_files').on('click', function() {
upcontrol.run();
});
}
},
preview : function() {
//upcontrol.preview() : preview uploading file
if (upcontrol.queue) {
var filesAmount = upcontrol.queue.length;
for (i = 0; i < filesAmount; i++) {
var reader = new FileReader();
reader.onload = function(event) {
var fimg = document.createElement('img')
fimg.src = event.target.result,
fimg.classList = "col-sm-6 col-md-6 col-lg-4 float-left center",
document.getElementById('gallery').appendChild(fimg);
}
reader.readAsDataURL(upcontrol.queue[i]);
}
}
},
run : function () {
// upcontrol.run() : proceed upload file
var xhr = new XMLHttpRequest(),
data = new FormData();
data.append('file-upload', upcontrol.queue[upcontrol.now]);
xhr.open('POST', './lockeroom/func/simple-upload.php', true);
xhr.onload = function (e) {
// SHOW UPLOAD STATUS
var fstat = document.createElement('div'),
txt = upcontrol.queue[upcontrol.now].name + " - ";
if (xhr.readyState === 4) {
if (xhr.status === 200) {
// SERVER RESPONSE
txt += xhr.responseText;
} else {
// ERROR
txt += xhr.statusText;
}
}
fstat.innerHTML = txt;
document.getElementById('upstat').appendChild(fstat);
// UPLOAD NEXT FILE
upcontrol.now++;
if (upcontrol.now < upcontrol.queue.length) {
upcontrol.run();
}
// ALL DONE
else {
upcontrol.now = 0;
upcontrol.queue = null;
document.getElementById('uploader').classList.remove('disabled');
}
};
xhr.send(data);
}
};
window.addEventListener("load", function () {
// IF DRAG-DROP UPLOAD SUPPORTED
if (window.File && window.FileReader && window.FileList && window.Blob) {
/* [THE ELEMENTS] */
var uploader = document.getElementById('uploader');
/* [VISUAL - HIGHLIGHT DROP ZONE ON HOVER] */
uploader.addEventListener("dragenter", function (e) {
e.preventDefault();
e.stopPropagation();
uploader.classList.add('highlight');
});
uploader.addEventListener("dragleave", function (e) {
e.preventDefault();
e.stopPropagation();
uploader.classList.remove('highlight');
});
/* [UPLOAD MECHANICS] */
// STOP THE DEFAULT BROWSER ACTION FROM OPENING THE FILE
uploader.addEventListener("dragover", function (e) {
e.preventDefault();
e.stopPropagation();
});
// ADD OUR OWN UPLOAD ACTION
uploader.addEventListener("drop", function (e) {
e.preventDefault();
e.stopPropagation();
uploader.classList.remove('highlight');
upcontrol.start(e.dataTransfer.files);
});
}
// FALLBACK - HIDE DROP ZONE IF DRAG-DROP UPLOAD NOT SUPPORTED
else {
document.getElementById('uploader').style.display = "none";
}
});
</script>
i used somthing like this and i got the best result and easy to understand.
function appendRows(){
$i++;
var html='';
html+='<div id="remove'+$i+'"><input type="file" name="imagefile[]" accept="image/*" onchange="appendloadFile('+$i+')"><img id="outputshow'+$i+'" height="70px" width="90px"><i onclick="deleteRows('+$i+')" class="fas fa-trash-alt"></i></div>';
$("#appendshow").append(html);
}
function appendloadFile(i){
var appendoutput = document.getElementById('outputshow'+i+'');
appendoutput.src = URL.createObjectURL(event.target.files[0]);
}
https://stackoverflow.com/a/59985954/8784402
ES2017 Way
// convert file to a base64 url
const readURL = file => {
return new Promise((res, rej) => {
const reader = new FileReader();
reader.onload = e => res(e.target.result);
reader.onerror = e => rej(e);
reader.readAsDataURL(file);
});
};
// for demo
const fileInput = document.createElement('input');
fileInput.type = 'file';
const img = document.createElement('img');
img.attributeStyleMap.set('max-width', '320px');
document.body.appendChild(fileInput);
document.body.appendChild(img);
const preview = async event => {
const file = event.target.files[0];
const url = await readURL(file);
img.src = url;
};
fileInput.addEventListener('change', preview);
$(function() {
// Multiple images preview in browser
var imagesPreview = function(input, placeToInsertImagePreview) {
if (input.files) {
var filesAmount = input.files.length;
for (i = 0; i < filesAmount; i++) {
var reader = new FileReader();
reader.onload = function(event) {
$($.parseHTML('<img>')).attr('src', event.target.result).appendTo(placeToInsertImagePreview);
}
reader.readAsDataURL(input.files[i]);
}
}
};
$('#gallery-photo-add').on('change', function() {
imagesPreview(this, 'div.gallery');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" multiple id="gallery-photo-add">
<div class="gallery">
$(function() {
// Multiple images preview in browser
var imagesPreview = function(input, placeToInsertImagePreview) {
if (input.files) {
var filesAmount = input.files.length;
for (i = 0; i < filesAmount; i++) {
var reader = new FileReader();
reader.onload = function(event) {
$($.parseHTML('<img>')).attr('src', event.target.result).appendTo(placeToInsertImagePreview);
}
reader.readAsDataURL(input.files[i]);
}
}
};
$('#gallery-photo-add').on('change', function() {
imagesPreview(this, 'div.gallery');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" multiple id="gallery-photo-add">
<div class="gallery">

While JavaScript File Reader With Pushing Data to Global Array

I have posted code below and trying to upload text files:
Problem is to store data in JavaScript array, ifileData always returns blank/null values.
<input type="file" name="ic-files[]" class="ic-input" multiple="true" />
<input type="file" name="ic-files[]" class="ic-input" multiple="true" />
<input type="file" name="ic-files[]" class="ic-input" multiple="true" />
<input type="file" name="ic-files[]" class="ic-input" multiple="true" />
<script>
var ifileData = new Array();
$(document).on('click','#start', function()
{
$('.ic-input').each(function()
{
if($(this).val() != "")
{
var inCorrectFile = $(this).get(0).files;
for (var i = 0; i < inCorrectFile.length; i++)
{
var reader = new FileReader();
reader.onload = function(e)
{
/* Temp Object */
var ipfileData = {};
var fileContent = this.result;
ipfileData['data'] = fileContent;
ifileData.push(ipfileData);
}
reader.readAsText(inCorrectFile[i], "UTF-8");
}
}
});
alert(JSON.stringify(ifileData));
});
</script>
also i've posted code to https://jsfiddle.net/3aexs7wp/3/
Try substituting change event for click event ; adjusting delegated selector to .ic-input
var ifileData = new Array();
$(document).on('change', '.ic-input', function() {
$('.ic-input').each(function() {
if ($(this).val() != "") {
var inCorrectFile = $(this).get(0).files;
for (var i = 0; i < inCorrectFile.length; i++) {
var reader = new FileReader();
reader.onload = function(e) {
/* Temp Object */
var ipfileData = {};
var fileContent = this.result;
ipfileData['data'] = fileContent;
ifileData.push(ipfileData);
console.log(ifileData)
}
reader.readAsText(inCorrectFile[i], "UTF-8");
}
}
});
// alert(JSON.stringify(ifileData));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<input type="file" name="ic-files[]" class="ic-input" multiple="true" />
jsfiddle https://jsfiddle.net/3aexs7wp/4/

PhoneGap - FormData Ajax submit does not work on device but works fine in browser

I am facing a problem in which same piece of code works fine in browser but doesn't work on device.
Below Code works fine in browser
HTML
<form id="snapitform" name="snapitform" action="" enctype="multipart/form-data" method="post" >
<input type="file"><br>
<br />
<div>Your Name</div>
<input type="text" id="yourname" />
<br />
<div>Phone Number</div>
<input type="text" id="phonenumber" />
<br />
<input type="button" value="Upload Snap IT Service" onclick="GetImageBLOBObjectFromFile(); return false;" />
<br />
<div id="snapitresult">
</div>
</form>
JavaScript
function GetImageBLOBObjectFromFile() {
var dataURL;
var file = document.querySelector('input[type=file]').files[0];
var reader = new FileReader();
reader.onloadend = function () {
dataURL = reader.result;
console.log("dataURL: "+ dataURL);
var sPicData = dataURItoImageJPGBlob(dataURL);
var sLanguage = "EN";
var sLongitude = "56.324319";
var sLatitude = "25.133403";
var sLocation = "Some location";
var sName = $("#yourname").val();
var sPhoneNumber = $("#phonenumber").val();
var sNotify = "Y";
var objForm = document.getElementById('snapitform');
SnapITServiceAPI.InitializeValues();
SnapITServiceAPI.getSnapITUploadService(objForm, sLanguage, sLongitude, sLatitude, sLocation, sName, sPhoneNumber, sNotify, sPicData);
}
if (file) {
reader.readAsDataURL(file);
} else {
dataURL = "";
}
}
function dataURItoImageJPGBlob(dataURI) {
console.log("dataURItoImageJPGBlob().. " );
var byteString = atob(dataURI.split(',')[1]);
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ab], { type: 'image/jpeg' });
}
/* -------------------SnapITServiceAPI ------------------------------- */
getSnapITUploadService: function(objForm, sLanguage, sLongitude, sLatitude, sLocation, sName, sPhoneNumber, sNotify, sPicData) {
var requestMode = 'UPLOADSERVICE';
var objFormData = new FormData(objForm);
objFormData.append('requestmode',requestMode);
objFormData.append('user',ApplicationConfig.getUserName());
objFormData.append('pass',ApplicationConfig.getUserPassword());
objFormData.append('lang',sLanguage);
objFormData.append('curlongitude',sLongitude);
objFormData.append('curlatitude',sLatitude);
objFormData.append('curlocation',sLocation);
objFormData.append('yourname',sName);
objFormData.append('phonenumber',sPhoneNumber);
objFormData.append('notify',sNotify);
objFormData.append('picdata',sPicData);
$.ajax({
type: "POST",
url: ApplicationConfig.getUATServerURL(),
dataType: "text",
mimeType:"multipart/form-data",
data: objFormData ,
processData: false,
crossDomain: true,
contentType: false,
cache: false,
success: this.OnSnapITReachITUploadSuccess,
error: this.OnSnapITReachITUploadError,
complete: this.OnSnapITReachITUploadComplete
});
return false;
}
Now using PhoneGap/Cordova, I have following code to take picture and upload it via the above code.
navigator.camera.getPicture(function (imageData) {
var smallImage = document.getElementById('snapItPicToUpload');
smallImage.style.display = 'block';
smallImage.src = imageData; //display Pic on the device then proceed for upload
window.resolveLocalFileSystemURI(imageData, gotFileEntry,
function (message) {
alert('Failed URI FileSystem: ' + message);
});
}, function (message) {
alert('Failed because: ' + message);
}, {
quality: 50,
destinationType: Camera.DestinationType.FILE_URI,
sourceType: Camera.PictureSourceType.CAMERA,
targetWidth: 100,
targetHeight: 100
});
var gotFileEntry = function(fileEntry) {
alert("got image : " + fileEntry.fullPath);
fileEntry.file( function(file) {
var reader = new FileReader();
reader.onloadend = function() {
alert("Read complete!");
sessionStorage.setItem("fileUpload", JSON.stringify(reader.result));
};
reader.readAsDataURL(file);
}, function (messgae) {
alert('Failed inside FileEnter: ' + message);
});
};
When I take picture and submit it to server then I receive Out of Memory error message.(Error Code: 00346).
Is something wrong with my code Or I have to change something while calling from device.
Unfortunately I don't have access to backend/server side. I was just given services to consume. So i don't know how they are implemented on the server side.

Categories