angular4 upload image and pass to server and save into database(express and mongoose, mongodb) - mongodb

Is there anyone knows how to upload an image within Angular 4 environment, then sending this data to the backend as express server, and using mongoose to store into mongodb? if anyone knows, please post the answer. Thank
File input
{{imgfile.errors | json}}
<div class="alert alert-danger"
*ngIf="size >= 300000">
<strong>
Can't upload this image. check image size!!!
</strong>
</div>
Script
onFileChange(event) {
let reader = new FileReader();
if(event.target.files && event.target.files.length > 0) {
console.log(event.target.files)
let file = event.target.files[0];enter code here
this.size = file.size;
console.log(file.size);
if (file.size <= 300000) {
this.picSize = true;
}
reader.onload = () => {
this.new_food.image = reader.result;
};
reader.readAsDataURL(file);
}
}

onFileChange(event) {
let reader = new FileReader();
if(event.target.files && event.target.files.length > 0) {
console.log(event.target.files)
let file = event.target.files[0];enter code here
this.size = file.size;
console.log(file.size);
if (file.size <= 300000) {
this.picSize = true;
}
reader.onload = () => {
this.new_food.image = reader.result;
};
reader.readAsDataURL(file);
}
}

Related

Can't figure out how to select items in the Facebook newsfeed for a Chome Extension

I'm working on a Chrome extension that inserts a button on every item in the Facebook newsfeed. I started off by using Tampermonkey to install a script that installs a button next to the subscribe video of every Youtube page (chrome-extension://dhdgffkkebhmkfjojejmpbldmpobfkfo/ask.html?aid=994ff494-1242-452f-a334-1bd616e18bb6), which worked fine.
Then I tried to modify it so it acts on the Facebook newsfeed, rather than the Youtube subscribe button. I changed the // match to go to facebook.com and targeting it to go after class='_3vuz', the Facebook div that houses the "like" button. But nothing happens when I go on Facebook; no button appears.
Here's my Tampermonkey code. Many thanks!
// ==UserScript==
// #name Facebook Fake News Button
// #namespace https://www.youtubeinmp3.com
// #version 1.2.2
// #description Adds a button to show you whether a Facebook article is true
// #author Ilana
// #match https://www.facebook.com/*
// #run-at document-end
// ==/UserScript==
function polymerInject(){
/* Create button */
var buttonDiv = document.createElement("div");
buttonDiv.style.width = "100%";
buttonDiv.id = "parentButton";
var addButton = document.createElement("button");
addButton.appendChild(document.createTextNode("Fake News"));
if(typeof(document.getElementById("iframeDownloadButton")) != 'undefined' && document.getElementById("iframeDownloadButton") !== null){
document.getElementById("iframeDownloadButton").remove();
}
addButton.style.width = "100%";
addButton.style.backgroundColor = "#181717";
addButton.style.color = "white";
addButton.style.textAlign = "center";
addButton.style.padding = "10px 0";
addButton.style.marginTop = "5px";
addButton.style.fontSize = "14px";
addButton.style.border = "0";
addButton.style.cursor = "pointer";
addButton.style.borderRadius = "2px";
addButton.style.fontFamily = "Roboto, Arial, sans-serif";
addButton.onclick = function () {
this.remove();
/* Add large button on click */
var addIframe = document.createElement("iframe");
addIframe.src = '//www.convertmp3.io/widget/button/?color=ba1717&video=' + window.location.href;
addIframe.style.width = "100%";
addIframe.style.border = "none";
addIframe.style.height = "60px";
addIframe.style.marginTop = "10px";
addIframe.style.overflow = "hidden";
addIframe.scrolling = "no";
addIframe.id = "iframeDownloadButton";
var targetElement = document.querySelectorAll("[id='meta']");
for(var i = 0; i < targetElement.length; i++){
if(targetElement[i].className.indexOf("ytd-watch") > -1){
targetElement[i].insertBefore(addIframe, targetElement[i].childNodes[0]);
}
}
};
buttonDiv.appendChild(addButton);
/* Find and add to target */
var targetElement = document.querySelectorAll("[class='_3vuz']");
for(var i = 0; i < targetElement.length; i++){
if(targetElement[i].className.indexOf("ytd-video-secondary-info-renderer") > -1){
targetElement[i].appendChild(buttonDiv);
}
}
/* Fix hidden description bug */
var descriptionBox = document.querySelectorAll("ytd-video-secondary-info-renderer");
if(descriptionBox[0].className.indexOf("loading") > -1){
descriptionBox[0].classList.remove("loading");
}
}
function standardInject() {
var pagecontainer=document.getElementById('page-container');
if (!pagecontainer) return;
if (/^https?:\/\/www\.facebook.com\/watch\?/.test(window.location.href)) run();
var isAjax=/class[\w\s"'-=]+spf\-link/.test(pagecontainer.innerHTML);
var logocontainer=document.getElementById('logo-container');
if (logocontainer && !isAjax) { // fix for blocked videos
isAjax=(' '+logocontainer.className+' ').indexOf(' spf-link ')>=0;
}
var content=document.getElementById('content');
if (isAjax && content) { // Ajax UI
var mo=window.MutationObserver||window.WebKitMutationObserver;
if(typeof mo!=='undefined') {
var observer=new mo(function(mutations) {
mutations.forEach(function(mutation) {
if(mutation.addedNodes!==null) {
for (var i=0; i<mutation.addedNodes.length; i++) {
if (mutation.addedNodes[i].id=='watch7-container' ||
mutation.addedNodes[i].id=='watch7-main-container') { // old value: movie_player
run();
break;
}
}
}
});
});
observer.observe(content, {childList: true, subtree: true}); // old value: pagecontainer
} else { // MutationObserver fallback for old browsers
pagecontainer.addEventListener('DOMNodeInserted', onNodeInserted, false);
}
}
}
function onNodeInserted(e) {
if (e && e.target && (e.target.id=='watch7-container' ||
e.target.id=='watch7-main-container')) { // old value: movie_player
run();
}
}
function finalButton(){
var buttonIframeDownload = document.createElement("iframe");
buttonIframeDownload.src = '//www.convertmp3.io/widget/button/?color=ba1717&video=' + window.location.href;
buttonIframeDownload.id = "buttonIframe";
buttonIframeDownload.style.width = "100%";
buttonIframeDownload.style.height = "60px";
buttonIframeDownload.style.paddingTop = "20px";
buttonIframeDownload.style.paddingBottom = "20px";
buttonIframeDownload.style.overflow = "hidden";
buttonIframeDownload.scrolling = "no";
document.getElementById("watch-header").appendChild(buttonIframeDownload);
}
function run(){
if(!document.getElementById("parentButton") && window.location.href.substring(0, 25).indexOf("facebook.com") > -1 && window.location.href.indexOf("watch?") > -1){
var parentButton = document.createElement("div");
parentButton.className = "yt-uix-button yt-uix-button-default";
parentButton.id = "parentButton";
parentButton.style.height = "23px";
parentButton.style.marginLeft = "28px";
parentButton.style.paddingBottom = "1px";
parentButton.onclick = function () {
this.remove();
finalButton();
};
document.getElementById("watch7-user-header").appendChild(parentButton);
var childButton = document.createElement("span");
childButton.appendChild(document.createTextNode("Download MP3"));
childButton.className = "yt-uix-button-content";
childButton.style.lineHeight = "25px";
childButton.style.fontSize = "12px";
parentButton.appendChild(childButton);
}
}
if(document.getElementById("polymer-app") || document.getElementById("masthead") || window.Polymer){
setInterval(function(){
if(window.location.href.indexOf("watch?v=") < 0){
return false;
}
if(document.getElementById("count") && document.getElementById("parentButton") === null){
polymerInject();
}
}, 100);
}
else{
standardInject();
}

How to load/configure IBM Daeja ViewONE in html?

All my requirement is to load daeja docviewer in html and running it using jsp file in jboss server
I have tried to load/configure IBM Daeja ViewONE using Html.I have included necessary jars and license files but it is not loading. Please help in resolving this and check i need to add/remove any thing to get this running
Jars added
Html :
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script language="javascript" type="text/javascript" src="viewone.js"></script>
<title>User Data</title>
</head>
<body>
<div>
<Object class="com.ibm.dv.client.Viewer" id="viewone" width="100%" height="100%" name="viewone">
<param name="trace" value="true">
<param name="tracenet" value="true">
<param name="tracefilter" value="true">
</Object>
</div>
</body>
</html>
``
viewone.js
function ViewOneBootstrap() { alert('1ds1');
this.logMessages = new Array();
this.debugMessages = new Array();
this.clientids = new Array();
this.codebase = null;
this.lastFocussed = null;
this.objectTag = "com.ibm.dv.client.Viewer";
this.instanceId = 1;
//document content clipboard
this.clipboard = new ViewOneClipboard();
this.getInstanceId = function() {
return "" + this.instanceId++;
}
this.addMessage = function(message) {
this.logMessages.push(message);
this.log(message)
};
this.clearMessages = function() {
this.logMessages = new Array();
};
this.log = function(message) {
if (this.debugMessages.length >= 100)
this.debugMessages.shift();
this.debugMessages.push(message);
if (window.console) {
if (window.console.debug)
window.console.debug(message);
else if (window.console.log)
window.console.log(message);
}
};
this.getHead = function() {
var headElem = null;
var oHead = document.getElementsByTagName('head');
if (oHead == null || oHead.length == 0) {
headElem = document.createElement();
document.appendChild(headElem);
} else {
headElem = oHead[0];
}
return headElem;
};
this.includeJS = function(sId, fileUrl, source) {
viewoneLoader.addMessage("Attaching script " + sId
+ (source == null ? "" : (" length=" + source.length)));
if ((source != null) && (!document.getElementById(sId))) {
var oHead = viewoneLoader.getHead();
var oScript = document.createElement("script");
oScript.type = "text/javascript";
oScript.id = sId;
oScript.defer = "true";
if (source == null) {
oScript.src = fileUrl;
} else {
oScript.text = source;
}
viewoneLoader.getHead().appendChild(oScript);
viewoneLoader.addMessage("Script attached");
}
};
var addMessage = this.addMessage;
this.addMessage('ViewOneBootstrap:init<>');
this.showMessages = function() {
var messages = "";
for (var i = 0; i < this.logMessages.length; i++) {
messages += this.logMessages[i];
messages += "\n";
}
alert(messages);
};
this.getHttpRequest = function() {
if (window.XMLHttpRequest)
return new XMLHttpRequest();
if (window.ActiveXObject)
return new ActiveXObject("MsXml2.XmlHttp");
};
this.loadScript = function(sId, url, postData) {
this.codebase = url;
this.postData = postData;
this.addMessage('ViewOneBootstrap.loadScript: ' + url);
var oXmlHttp = this.getHttpRequest();
var scriptLoad = this.includeJS;
var loadFailed = this.loadError;
oXmlHttp.onreadystatechange = function() {
if (oXmlHttp.readyState == 4) {
if (oXmlHttp.status == 200 || oXmlHttp.status == 304) {
viewoneLoader.addMessage("Script downloaded");
scriptLoad(sId, url, oXmlHttp.responseText);
} else {
var isCrossDomain = true;
if (url.indexOf("http://") != 0 && url.indexOf("https://") != 0)
isCrossDomain = false;
// Can't be cross domain unless the URL starts http: or https:
else if (url.indexOf("https:") == 0 && window.location.protocol != "https:")
isCrossDomain = false;
else if (url.indexOf("http:") == 0 && window.location.protocol != "http:")
isCrossDomain = false;
else {
var url2 = url.replace(/^https?:\/\//, "");
var match = url2.match(/^[^\/]+/);
if (match) {
var domain = match[0];
if (window.location.host == domain)
isCrossDomain = false;
}
}
if (isCrossDomain && oXmlHttp.status == 0) {
loadFailed("Cannot load ViewONE.\n"
+ "Likely reasons include:\n"
+ "- Cross domain resource loading is not supported by this browser\n"
+ "- Cross domain resource loading is not configured correctly on the server\n"
+ "- There was a temporary network issue when loading ViewONE\n"
+ "- This web browser has incorrectly cached some data (please empty the cache)");
} else {alert('error 2');
viewoneLoader.addMessage('XML request error: '
+ oXmlHttp.statusText + ' (' + oXmlHttp.status
+ ')');
viewoneLoader.showMessages();
}
}
}
};
oXmlHttp.open('GET', url, true);
if (oXmlHttp.setRequestHeader)
oXmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
oXmlHttp.send(null);
};
this.includeJS = function(sId, fileUrl, source) {
viewoneLoader.addMessage("Attaching script " + sId
+ (source == null ? "" : (" length=" + source.length)));
if (!(source == null && fileUrl == null)
&& (!document.getElementById(sId))) {
var oHead = viewoneLoader.getHead();
var oScript = document.createElement("script");
oScript.type = "text/javascript";
oScript.id = sId;
oScript.defer = "true";
if (source == null) {
oScript.src = fileUrl;
} else {
oScript.text = source;
}
oHead.appendChild(oScript);
viewoneLoader.addMessage("Script attached");
}
};
this.addMetaTag = function(name, content) {
this.addMessage('ViewOneBootstrap.addMetaTag');
var oHead = this.getHead();
var mTag = document.createElement("meta");
mTag.name = name;
mTag.content = content;
oHead.appendChild(mTag);
};
this.loadCompleted = function() {
this.addMessage("ViewOneBootstrap.loadCompleted: viewer ready to start");
if (window.notifyViewONECodeInit)
{
window.notifyViewONECodeInit();
}
};
this.loadError = function(message) {
addMessage(message);
if (window.deinitPercentage) {
window.deinitPercentage();
addMessage("Percentage display removed");
}
if (window.showViewoneLoadError)
window.showViewoneLoadError(message);
else
alert(message);
}
}
function ViewOneClipboard() {
this.content = null;
this.putContent = function(jsonBlob)
{
//viewoneLoader.log("added to clipboard: " + jsonBlob);
this.content = jsonBlob;
}
this.getContent = function()
{
//viewoneLoader.log("retrieved from clipboard: "+ this.content);
return this.content;
}
}
var viewoneLoader = new ViewOneBootstrap();
//viewoneLoader.addMetaTag('viewone_ajax::gwt:property', 'baseUrl=filenet/v1files/?v=9001&op=resource&file=');
//viewoneLoader.loadScript('viewoneLoader', 'filenet/v1files/?v=9001&op=resource&file=viewone.cache.js', '');
viewoneLoader.com_viewone_instance = '1';
viewoneLoader.com_viewone_instancel = {"start":"","end":"","num":"", "modInf": [{"type":"2"}, {"type":"3"}, {"type":"4"}, {"type":"5"}, {"type":"6"}, {"type":"8"}, {"type":"G"}, {"type":"I"}, {"type":"M"}],"trial":false,"company":"","country":"","support":false,"contact":"","rProduct":"","rCompany":"","rEmail":"","rSite":"","rAllowIgnorePro":false,"testBuild":false,"legacyFeatures":false};
viewoneLoader.loadingMessage = 'IBM Daeja ViewONE Virtual 5.0.3';
viewoneLoader.version = "9001";
viewoneLoader.displayversion = "5.0.3";
viewoneLoader.fulldisplayversion = "5.0.3 iFix 1";
viewoneLoader.acceptLanguages = ["en-US","en"];
If you remove DIV tags around Daeja object, the page will get loaded.
If you want to keep the DIV, you need to change width and height value from percentage to absolute px value. Otherwise it won't work. Don't know why and really don't like the way it is.

upload image using javascript and xajax to MySql Blob

I want to upload images to database, but I dont know how to receive this file.
//html
<input type="text" id="txtName">
<input type="file" id="image" onchange="sendImage()">
//Javascript
function sendImage()
{
var name = $('#txtName').val();
var image = $('#image').val(); //is this the way to send the image?
xajax_SaveImage(name, image);
}
//xajax
//with string I dont have problems for receive, but how receive I the image?
function SaveImage($name, $image)
{
//How here I convert the image to binary for to save in Mysql
}
You can do this: base64 is the image data, upload that data to database
File.prototype.convertToBase64 = function(callback){
var reader = new FileReader();
reader.onload = function(e) {
callback(e.target.result)
};
reader.onerror = function(e) {
callback(null, e);
};
reader.readAsDataURL(this);
};
$("#image").on('change',function(){
var selectedFile = this.files[0];
if (!selectedFile.name.match(/.(jpg|jpeg|png|gif)$/i)) {
}
else {
selectedFile.convertToBase64(function(base64){
//base64 is the base64 value of the image, use this to send to database...
})
}
});
Code snippet example:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="image">
<script>
File.prototype.convertToBase64 = function(callback){
var reader = new FileReader();
reader.onload = function(e) {
callback(e.target.result)
};
reader.onerror = function(e) {
callback(null, e);
};
reader.readAsDataURL(this);
};
$("#image").on('change',function(){
var selectedFile = this.files[0];
if (!selectedFile.name.match(/.(jpg|jpeg|png|gif)$/i)) {
}
else {
selectedFile.convertToBase64(function(base64){
console.log(base64);
})
}
});
</script>
In your template (smarty)
<div id="imageplaceholder" class="left shadow"><p>Place<br />Image<br />here.<br />(drag&drop)</p></div>
<div id="image">
<div id="imageborder" class="left shadow">{if $persondata.imagesize gt 0}<img src="getimage.php?h={$smarty.session.verify}&id={$persondata.id}" />{/if}</div>
</div><div id="imagetools" class="left">
<div id="imagehelp" class="imagetool help radius3 shadow"></div>
<div id="imagenew" class="imagetool new radius3 shadow"></div>
<div id="imagezoomin" class="imagetool zoomin radius3 shadow"></div>
<div id="imagezoomout" class="imagetool zoomout radius3 shadow"></div>
<div id="imageok" class="imagetool ok radius3 shadow"></div>
</div>
js part uses filedrop.
FileDrop JavaScript classes | by Proger_XP https://github.com/ProgerXP/FileDrop
$('#imageplaceholder').filedrop({
// The name of the $_FILES entry:
paramname:'pic',
url: '/img_file.php', //this is the PHP file used for processing
allowedfiletypes: ['image/jpeg','image/png','image/gif'],
uploadFinished:function(i,file,response){
// remove placeholder
// add Image
// $.data(file).addClass('done');
// response is the JSON object that img_file.php returns
$('#imageplaceholder').hide();
loadImage(file);
$('#image').show();
$('#imagetools .help').show();
$('#imagetools .zoomin').show();
$('#imagetools .zoomout').show();
$('#imagetools .ok').show();
$('#imagetools .ok').click(function(){
var img = $('#imageborder').find('img');
var offset = img.offset();
var pos = $('#imageborder').position();
offset.top = pos.top - offset.top;
offset.left = pos.left - offset.left;
var name = $('#imageborder').attr('name');
var scale = $('#imageborder').attr('scale');
var id = $('input[name=user_id]').val();
var hash = $('#hash').val();
var ret = xajax_settings_action({ xjxfun: 'settings_action' }, { parameters: ['saveimage',hash,id,name,offset,scale] }, { mode: 'synchronous' });
if(ret != 0)
{
$('#imagetools .help').hide();
$('#imagetools .zoomin').hide();
$('#imagetools .zoomout').hide();
$('#imagetools .ok').hide();
$('#imagetools .cancel').removeClass('cancel').addClass('new');
}
});
},
rename: function(name) {
// name in string format
// must return alternate name as string
var date = new Date();
// get file type
var typ = name.split('.',2);
// buffer name for save response
$('#imageborder').attr('name',date.getTime() + "." + typ[1]);
return date.getTime() + "." + typ[1];
},
// Called before each upload is started
beforeEach: function(file){
if(!file.type.match(/^image\//)){
jAlert('Only images are allowed!');
// Returning false will cause the
// file to be rejected
return false;
}
},
});
img_file.php
<?php
// Set the directory where files will be saved
$upload_dir = '/tmp/';
$allowed_ext = array('jpg','jpeg','png','gif');
if(strtolower($_SERVER['REQUEST_METHOD']) != 'post'){
exit_status('Error! Wrong HTTP method!');
}
if(array_key_exists('pic',$_FILES) && $_FILES['pic']['error'] == 0 ){
$pic = $_FILES['pic'];
if(!in_array(get_extension($pic['name']),$allowed_ext)){
exit_status('Only '.implode(',',$allowed_ext).' files are allowed!');
}
// Move the uploaded file from the temporary
// directory to the uploads folder:
if( move_uploaded_file($pic['tmp_name'], $upload_dir.$pic['name']) ){
exit_status('File was uploaded successfuly!');
}
}
exit_status('Something went wrong with your upload!');
// Helper functions
function exit_status($str){
echo json_encode(array('status'=>$str));
exit;
}
function get_extension($file_name){
$ext = explode('.', $file_name);
$ext = array_pop($ext);
return strtolower($ext);
}
?>
I use simpleimage.php from Simon Jarvis to scale and crop the image.
private function save_FileDB($id,$name,$pos,$scale)
{
$upload_dir = "/tmp/";
$response = new xajaxResponse();
$userid = $_SESSION['userid'];
$binFile = $upload_dir.$name;
if (isset($binFile) && $binFile != "none") {
$simage = new SimpleImage();
$simage->load($binFile);
$simage->scale($scale*100);
$simage->crop($pos[left],$pos[top],175,200);
$simage->save($binFile);
$binFile_size = filesize($binFile);
$ext = explode('.', $name);
$ext = strtolower( array_pop($ext) );
switch($ext){
case 'jpg': $binFile_type = 'image/jpeg'; break;
case 'png': $binFile_type = 'image/png'; break;
case 'gif': $binFile_type = 'image/gif'; break;
}
$data = addslashes(fread(fopen($binFile, "r"), $binFile_size ));
$qs = "update persondata set image='$data', imagetype='$binFile_type', imagesize='$binFile_size' where id=$id";
$ret = $this->exec_query($qs);
unlink($binFile);
$response->setReturnValue("1");
return $response;
}
$response->setReturnValue("0");
return $response;
}

File Uploader - Upload excel file and convert it into JSON and bind to the table

After uploading the excel file on file uploader control in sapui5, excel file is converted in to JSON using following code.
handleExcelUpload : function(e) {
this._import(e.getParameter("files")
&& e.getParameter("files")[0]);
},
_import : function(file) {
if (file && window.FileReader) {
var reader = new FileReader();
that = this;
result = {};
var data;
reader.onload = function(e) {
var data = e.target.result;
var wb = XLSX.read(data, {
type : 'binary'
});
wb.SheetNames
.forEach(function(sheetName) {
var roa = XLSX.utils
.sheet_to_row_object_array(wb.Sheets[sheetName]);
if (roa.length > 0) {
result[sheetName] = roa;
}
});
};
reader.readAsBinaryString(file);
};
},
Note : I have used jszip.js and xlsx.js library to convert excel to JSON
Now in result variable I am getting JSON format data, and this data I have bind to the table.
The issue is, JSON binding with table is working fine with the Chrome, Firefox latest browser but, its not working on in IE 11 browser or it's showing only No data in table
Is there any other file reader method which supports IE11?
Yes I got answer.. I found readAsArrayBuffer method in Javascript which is compatible for all latest browser even in IE11
Here is my working code.
XML code:
<FileUploader id="fileUploader" name="myFileUpload"
class="sapUiSmallMarginEnd" uploadUrl="upload/" width="400px"
tooltip="Upload your file to the local server" uploadComplete="handleUploadComplete"
change="handleExcelUpload" placeholder="Please Select File" />
JS code:
handleExcelUpload : function(e) {
this._import(e.getParameter("files")
&& e.getParameter("files")[0]);
},
_import : function(file) {
debugger;
if (file && window.FileReader) {
var reader = new FileReader();
that = this;
//result = {};
//var data;
reader.onload = function(evt) {
var data = evt.target.result;
//var xlsx = XLSX.read(data, {type: 'binary'});
var arr = String.fromCharCode.apply(null, new Uint8Array(data));
var xlsx = XLSX.read(btoa(arr), {type: 'base64'});
result = xlsx.Strings;
result = {};
xlsx.SheetNames.forEach(function(sheetName) {
var rObjArr = XLSX.utils.sheet_to_row_object_array(xlsx.Sheets[sheetName]);
if(rObjArr.length > 0){
result[sheetName] = rObjArr;
}
});
return result;
that.b64toBlob(xlsx, "binary");
};
reader.readAsArrayBuffer(file);
};
},
b64toBlob : function(b64Data, contentType) {
contentType = contentType || '';
var sliceSize = 512;
b64Data = b64Data.replace(/^[^,]+,/, '');
b64Data = b64Data.replace(/\s/g, '');
var byteCharacters = Base64.decode(b64Data);
var byteArrays = [];
for (var offset = 0; offset < byteCharacters.length;offset += sliceSize){
var slice = byteCharacters.slice(offset, offset + sliceSize);
var byteNumbers = new Array(slice.length);
for (var i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
var blob = new Blob(byteArrays, {
type : contentType
});
}
After this add the base64 util
var Base64 = {}; // Base64 namespace
Base64.code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
Base64.encode = function(str, utf8encode) {
utf8encode = (typeof utf8encode == 'undefined') ? false : utf8encode;
var o1, o2, o3, bits, h1, h2, h3, h4, e=[], pad = '', c, plain, coded;
var b64 = Base64.code;
plain = utf8encode ? Utf8.encode(str) : str;
c = plain.length % 3;
if (c > 0) { while (c++ < 3) { pad += '='; plain += '\0'; } }
for (c=0; c<plain.length; c+=3) {
o1 = plain.charCodeAt(c);
o2 = plain.charCodeAt(c+1);
o3 = plain.charCodeAt(c+2);
bits = o1<<16 | o2<<8 | o3;
h1 = bits>>18 & 0x3f;
h2 = bits>>12 & 0x3f;
h3 = bits>>6 & 0x3f;
h4 = bits & 0x3f;
e[c/3] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
}
coded = e.join('');
coded = coded.slice(0, coded.length-pad.length) + pad;
return coded;
}
Base64.decode = function(str, utf8decode) {
utf8decode = (typeof utf8decode == 'undefined') ? false : utf8decode;
var o1, o2, o3, h1, h2, h3, h4, bits, d=[], plain, coded;
var b64 = Base64.code;
coded = utf8decode ? Utf8.decode(str) : str;
for (var c=0; c<coded.length; c+=4) {
h1 = b64.indexOf(coded.charAt(c));
h2 = b64.indexOf(coded.charAt(c+1));
h3 = b64.indexOf(coded.charAt(c+2));
h4 = b64.indexOf(coded.charAt(c+3));
bits = h1<<18 | h2<<12 | h3<<6 | h4;
o1 = bits>>>16 & 0xff;
o2 = bits>>>8 & 0xff;
o3 = bits & 0xff;
d[c/4] = String.fromCharCode(o1, o2, o3);
// check for padding
if (h4 == 0x40) d[c/4] = String.fromCharCode(o1, o2);
if (h3 == 0x40) d[c/4] = String.fromCharCode(o1);
}
plain = d.join(''); // join() is far faster than repeated string concatenation in IE
return utf8decode ? Utf8.decode(plain) : plain;
}
Try this, without external library:
/*In the function "Press" */
var file = oFileUploader.getFocusDomRef().files[0];
if (file && window.FileReader) {
var reader = new FileReader();
var that = this;
reader.onload = function(e) {
var strCSV = e.target.result;
var arrCSV = strCSV.replace(/['",]/g, '').split(/[↵\n]+/).join(';').split(';');
var noOfCols = 11; // 11 Columns
var hdrRow = arrCSV.splice(0, noOfCols);
var oData = [];
while (arrCSV.length > 0) {
var obj = {};
var row = arrCSV.splice(0, noOfCols)
if (row.length > 1) {
for (var i = 0; i < row.length; i++) obj[hdrRow[i].replace(/\r/g, "")] = row[i].trim();
oData.push(obj) // Data Json
}
}
oTable.setModel(new sap.ui.model.json.JSONModel(oData)); // Binding model
};
reader.readAsText(file, 'ISO-8859-1');
}
Regards.
Check the code in my gist
Upload_CSV.js
Place this in the controller to parse the file using JS client side
var fU = this.getView().byId("idfileUploader");
var domRef = fU.getFocusDomRef();
var file = domRef.files[0];
var reader = new FileReader();
var params = "ItemsJson=";
reader.onload = function(oEvent) {
var strCSV = oEvent.target.result;
var arrCSV = strCSV.match(/[\w .]+(?=,?)/g);
var noOfCols = 3;
var headerRow = arrCSV.splice(0, noOfCols);
var data = [];
while (arrCSV.length > 0) {
var obj = {};
var row = arrCSV.splice(0, noOfCols);
for (var i = 0; i < row.length; i++) {
obj[headerRow[i]] = row[i].trim();
}
data.push(obj);
}
data.reverse();
var json = JSON.stringify(data); // send to the backend
if I did not answer you please tell me

multiple file upload using html5 drag-and-drop fails as multiple files get same content

I need to transfer all the files dropped on an element to a server using HTML5 drag and drop.
I provided the corresponding js code below. I have a servlet in the server side to collect the files and put it in a folder. This is working fine if I drop 1 or 2 files on the page. But, if i drop 4-10 files, all the files are getting created in the server but multiple files are set to same content and some files content is 0K.
Can any of you please tell me how to achieve the correct behavior.
My requirement is similar to gmail attachments!!
Any solution which makes a sequential upload of files is much appreciable.
/*
* Upload files to the server using HTML 5 Drag and drop from the folders on your local computer
*/
function uploader(place, status, target, show) {
// Upload image files
upload = function(file) {
// Firefox 3.6, Chrome 6, WebKit
if(window.FileReader) {
// Once the process of reading file
this.loadEnd = function() {
bin = reader.result;
xhr = new XMLHttpRequest();
xhr.open('POST', target+'?up=true', false);
var body = bin;
xhr.setRequestHeader('content-type', 'multipart/form-data;');
xhr.setRequestHeader("file-name", file.name );
xhr.setRequestHeader("mime-type", file.type );
// Firefox 3.6 provides a feature sendAsBinary ()
if(xhr.sendAsBinary != null) {
xhr.sendAsBinary(body);
// Chrome 7 sends data but you must use the base64_decode on the PHP side
} else {
xhr.open('POST', target+'?up=true&base64=true', true);
xhr.setRequestHeader('UP-FILENAME', file.name);
xhr.setRequestHeader('UP-SIZE', file.size);
xhr.setRequestHeader('UP-TYPE', file.type);
xhr.send(window.btoa(bin));
}
if (show) {
var newFile = document.createElement('div');
newFile.innerHTML = 'Loaded : '+file.name+' size '+file.size+' B';
document.getElementById(show).appendChild(newFile);
}
if (status) {
document.getElementById(status).innerHTML = 'Loaded : 100%<br/>Next file ...';
}
};
// Loading errors
this.loadError = function(event) {
switch(event.target.error.code) {
case event.target.error.NOT_FOUND_ERR:
document.getElementById(status).innerHTML = 'File not found!';
break;
case event.target.error.NOT_READABLE_ERR:
document.getElementById(status).innerHTML = 'File not readable!';
break;
case event.target.error.ABORT_ERR:
break;
default:
document.getElementById(status).innerHTML = 'Read error.';
}
};
// Reading Progress
this.loadProgress = function(event) {
if (event.lengthComputable) {
var percentage = Math.round((event.loaded * 100) / event.total);
document.getElementById(status).innerHTML = 'Loaded : '+percentage+'%';
}
};
// Preview images
this.previewNow = function(event) {
bin = preview.result;
var img = document.createElement("img");
img.className = 'addedIMG';
img.file = file;
img.src = bin;
document.getElementById(show).appendChild(img);
};
reader = new FileReader();
// Firefox 3.6, WebKit
if(reader.addEventListener) {
reader.addEventListener('loadend', this.loadEnd, false);
if (status != null)
{
reader.addEventListener('error', this.loadError, false);
reader.addEventListener('progress', this.loadProgress, false);
}
// Chrome 7
} else {
reader.onloadend = this.loadEnd;
if (status != null)
{
reader.onerror = this.loadError;
reader.onprogress = this.loadProgress;
}
}
var preview = new FileReader();
// Firefox 3.6, WebKit
if(preview.addEventListener) {
preview.addEventListener('loadend', this.previewNow, false);
// Chrome 7
} else {
preview.onloadend = this.previewNow;
}
// The function that starts reading the file as a binary string
reader.readAsBinaryString(file);
// Preview uploaded files
if (show) {
preview.readAsDataURL(file);
}
// Safari 5 does not support FileReader
} else {
xhr = new XMLHttpRequest();
xhr.open('POST', target+'?up=true', true);
xhr.setRequestHeader('UP-FILENAME', file.name);
xhr.setRequestHeader('UP-SIZE', file.size);
xhr.setRequestHeader('UP-TYPE', file.type);
xhr.send(file);
if (status) {
document.getElementById(status).innerHTML = 'Loaded : 100%';
}
if (show) {
var newFile = document.createElement('div');
newFile.innerHTML = 'Loaded : '+file.name+' size '+file.size+' B';
document.getElementById(show).appendChild(newFile);
}
}
};
// Function drop file
this.drop = function(event) {
event.preventDefault();
var dt = event.dataTransfer;
var files = dt.files;
for (var i = 0; i<files.length; i++) {
var file = files[i];
upload(file);
}
};
// The inclusion of the event listeners (DragOver and drop)
this.uploadPlace = document.getElementById(place);
this.uploadPlace.addEventListener("dragover", function(event) {
event.stopPropagation();
event.preventDefault();
}, true);
this.uploadPlace.addEventListener("drop", this.drop, false);
}
Thank you.
I spent sometimes this morning in analyzing the same code from html5uploader. With some lucks, I found the root cause.
Change reader = new FileReader(); to var reader = new FileReader(); should solve the issue.
I bet this is because javascripts behaviour of auto-declaring undeclared variable as global variable. This caused the reader variable being reused by all the uploade(file) calls when more than one file is dropped to the browser.
Cheers!