How do I accept file uploads from pasting a file into the browser? - forms

Accepting image uploads from a paste into the browser window is much easier than traditional file upload form inputs and even the newer style drag 'n' drop file uploads.
How do I implement it?

Here's an example PHP/JavaScript page that accepts drag 'n' drop image uploads. It's not dependent on PHP though - you could adapt it quite easily to work with another server-based language. This code was based on a snippet I found on jsFiddle by someone called Nick.
This is a full page - so you should be able to copy the code below and put it in a file on your web-server as-is (if you're not running PHP then you'll need to update the PHP code at the top or point the form to your own form handler script).
<?php
if (!empty($_POST)) {
// Handle the POSTed data here - the image is actually base64 encoded data in
// the $_POST['myTextarea'] variable which you can run through the base64_decode()
// function and then write to a file
$pos = strpos($_POST['myTextarea'], 'base64,');
$encoded = substr($_POST['myTextarea'], $pos + 7);
$raw = base64_decode($encoded);
// Show the base64 encoded $data - use the $raw variable when writing to a file
var_dump($_POST);
exit;
}
?>
<!DOCTYPE html >
<html>
<body>
<h1>File upload using paste</h1>
<p>
You can paste an image, which is on your clipboard, into this window and it will appear below.
If you use Windows you can press <b>PrtScr</b> to get a screenshot on your clipboard. Then
press <b>CTRL+V</b> to paste it into this document.
</p>
<!-- PUT THE ADDRESS OF YOUR FORM HANDLER SCRIPT IN THE ACTION ATTRIBUTE -->
<form action="" method="post">
<div id="form-elements-container">
<input type="text" value="An example text input..." name="myTextInput"><br />
<input type="submit" value="Submit form"><br />
</div>
</form>
<!-- THIS IS WHERE THE IMAGE THUMBNAILS WILL APPEAR -->
<div id="images-container"></div>
<script>
counter = 0;
document.body.onpaste = function (e)
{
// use event.originalEvent.clipboard for newer chrome versions
var items = (e.clipboardData || e.originalEvent.clipboardData).items;
// Find pasted image among pasted items
var blob = null;
for (var i=0; i<items.length; i++) {
if (items[i].type.indexOf("image") === 0) {
blob = items[i].getAsFile();
}
}
// Load image if there is a pasted image
if (blob !== null) {
var reader = new FileReader();
reader.onload = function(e)
{
// Create a new image object from the pasted data
var img = new Image();
img.src = e.target.result;
img.width = 128;
img.height = 128;
img.style.margin = '5px';
// Append the file to the document
document.getElementById('images-container').appendChild(img);
// Add a new textarea to the form
var textarea = document.createElement('textarea');
textarea.name = 'myTextarea_' + counter++;
textarea.value = img.src;
textarea.style.width = '200px';
textarea.style.height = '200px';
document.getElementById('form-elements-container').appendChild(textarea);
};
reader.readAsDataURL(blob);
}
}
</script>
</body>
</html>

Related

How to import an Excel file in to a database using angularJS1, hibernate(4.3.5), Spring(4.2.4)?

I want to import an Excel file into my database using angularJS1, Hibernate 4.3.5, Spring mvc 4.2.4. The Excel file is imported via a window (table consisting of children "last name, first name", and parents), the table was filled before manually. The goal now is to fill the table automatically by importing an Excel file. I can read the Excel file on google (json format), but I can not import it into my database. The project consists of a front part (angularJS1) and a back part (hibernate, postgresSQL, DAO). Could you help me please ? This is since Thursday that I seek a solution. Thank you
Here is the code to read my excel file in json format : file : ... Controller.js (front part)
$scope.uploadFile = function (element) {
var file = element.files[0];
console.log("FILE", file);
var reader = new FileReader();
reader.onload = function (event) {
var data = event.target.result;
/*Call XLSX*/
var workbook = XLSX.read(data, {
type: 'binary'
});
/* DO SOMETHING WITH workbook HERE */
var first_sheet_name = workbook.SheetNames[0];
/* Get worksheet */
var worksheet = workbook.Sheets[first_sheet_name];
var excelData = XLSX.utils.sheet_to_json(worksheet);
console.log("EXCELDATA", excelData);
}
}
Here is a sample codepen example created for you.
angular.module('app', [])
.controller('ExcelReadCtrl', function($scope) {
$scope.data = [{firstName:'AAA',lastName:'BBB',age:30}];
$scope.READ = function() {
/*Checks whether the file is a valid excel file*/
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.xlsx|.xls)$/;
var xlsxflag = false; /*Flag for checking whether excel is .xls format or .xlsx format*/
if ($("#ngexcelfile").val().toLowerCase().indexOf(".xlsx") > 0) {
xlsxflag = true;
}
var reader = new FileReader();
reader.onload = function (e) {
var data = e.target.result;
if (xlsxflag) {
var workbook = XLSX.read(data, { type: 'binary' });
}
else {
var workbook = XLS.read(data, { type: 'binary' });
}
var sheet_name_list = workbook.SheetNames;
var cnt = 0;
sheet_name_list.forEach(function (y) { /*Iterate through all sheets*/
if (xlsxflag) {
var exceljson = XLSX.utils.sheet_to_json(workbook.Sheets[y]);
}
else {
var exceljson = XLS.utils.sheet_to_row_object_array(workbook.Sheets[y]);
}
if (exceljson.length > 0) {
for (var i = 0; i < exceljson.length; i++) {
$scope.data.push(exceljson[i]);
$scope.$apply();
}
}
});
}
if (xlsxflag) {
reader.readAsArrayBuffer($("#ngexcelfile")[0].files[0]);
}
else {
reader.readAsBinaryString($("#ngexcelfile")[0].files[0]);
}
};
});
<html ng-app="app">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.7.7/xlsx.core.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xls/0.7.4-a/xls.core.min.js"></script>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"
crossorigin="anonymous"></script>
</head>
<body>
<div ng-app>
<h2>Excel Format should be same as table below, xls.core.min.js reads first row as headers</h2>
<div ng-controller="ExcelReadCtrl">
<form>
<input type="file" id="ngexcelfile" />
<input type="button" value="Read Data" ng-click="READ()" />
<br />
<br />
<table border=1>
<thead>
<tr>
<th>Last Name</th>
<th>First Name</th>
<th>Age</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in data">
<td>{{item.lastName}}</td>
<td>{{item.firstName}}</td>
<td>{{item.age}}</td>
</tr>
</tbody>
</table>
</form>
</div>
</div>
</body>
</html>
your excel format must be same as data you are trying to load.
Here is example format.
Once you load Excel data is stored in $scope.data use same to pass to backend
Instead of trying to read Excel on Front-End side just upload your excel to the server. Excel Reading via JS will consume a significant amount of MEM in browser.
On Java side its quite easy to read/Write Excel all you need is Apache POI
For Excel reading ref : https://www.mkyong.com/java/apache-poi-reading-and-writing-excel-file-in-java/
Once you done with excel reading, you can pass required data to hibernate to store in DB.
I have to read the excel file on the front because it is the user who update the data in the table by importing the Excel file through a upload interface.

How to insert a button in TinyMCE Editor to insert a local file as RAW image at current position?

How can i add a custom/default button to the TinyMCE Editor, to be able to select a local image and insert it as RAW (BASE64) image at current position in editor?
I just tried this from this answer.
window.onload = function () {
document.getElementById("fileName").onchange = function () {
var reader = new FileReader();
reader.readAsDataURL(this.files[0]);
reader.onload = function () {
console.log(reader.result);
document.getElementById("img").src = reader.result;
};
reader.onerror = function (error) {
console.log('Error: ', error);
};
};
};
<input type="file" name="fileName" id="fileName" /><br />
<img src="https://dummyimage.com/250x75/000/fff.png&text=Select+an+Image" id="img" style="max-width: 250px; max-height: 75px;" />
Using the above URL (see console or inspect element and find the src) and with inserting an image at the current position, you can insert the image inside the document at the current position of caret.

Tinymce Editor Plugin adding p tags

I have custom editor toolbar plugin which inserts html tags. The tag opens with div. Every time when page is saved or published the editor adds a new p tag above it.
here is the image
IMG tag drifts after publish I see a new p tag is inserted.
The Img being replaced by an html before saving
<p>
<div class="ssimage_code">
<img src="src_path0" alt=""/ >
<img src="src_path1" alt="" / >
</div>
</p>
I want to see if it gets solved by replacing a p tag instead of a img tag.
How do I access the parent tag from Node?
getParent does not work
Code
ed.serializer.addNodeFilter('img', function(nodes, name, args) {
var i = nodes.length, node;
while (i--) {
node = nodes[i];
if ((node.attr('class') || '').indexOf('slider_toimg') !== -1) {
self.imgToslidercode(node, args);
}
}
});
imgToslidercode:function(node,args){
insertcode = '';
node.replace(insertcode);
}
What I am looking here is?
node.getParent().replace(insertcode);

how to upload mulitiple file with expressjs?

this is my html
<form action="/keys/upload" method="post" enctype="multipart/form-data">
<ul>
<li><label>文件</label><input type="file" name="keys" multiple></li>
<li><input type="submit" value="submit"></li>
</ul>
</form>
this is my handle function
app.post('/keys/upload',keysRoutes.addKeys);
var addKeys=function(req,res){
var temppaths=req.files.keys[0].path;
console.log(temppaths);
res.end(JSON.stringify(temppaths));
};
here if i upload more than one file,then req.files.keys[0].path works fine,but when i only upload one file,it goes wrong,i have to replace it as req.files.keys.path. i don,t know how many files will be upload,so what should i do?
sometimes req.files.keys is array,sometimes req.files.keys is object.
Seems to me that you should check if it's an array or an object; when it's not an array, wrap it into one:
var paths = req.files.keys || [];
if (! (paths instanceof Array) ) {
paths = [ paths ];
}
I find a method,I think I can use
var paths=[].concat(paths);
then paths will always be an array

phonegap form submission wthout image or jquery

This is what I have below, the only way I can submit my form is by browsing for an image.
Can somebody please tell me how to submit this with a button, preferably without jQuery.
I only want to submit a form with text, no images. Thanks!
function browse()
{
navigator.camera.getPicture(uploadPhoto,
function(message) { alert('get picture failed'); },
{
quality: 50,
destinationType: navigator.camera.DestinationType.FILE_URI,
sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY
}
);
}
function uploadPhoto(imageURI)
{
var options = new FileUploadOptions();
options.fileKey="file";
options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
options.mimeType="image/jpeg";
var params = {};
params.value1 = "test";
params.value2 = document.getElementById('file_name').value + "";
}
I think what you're asking is how you can submit an image from the camera to your server without having to have a file input form element, where the user has to browse for the file etc.
The easiest answer is simply not to store the image as a file, but keep it as a base64 string. To do this, change your destination type to
destinationType: Camera.DestinationType.DATA_URL
The parameter to your success function will now be a base64 string, which you can send to your server much like any other string. You'll then need to base64_decode it server-side, and then write it to the disk.
Try a normal HTML form:
<form action="/post" method="post">
Input: <input type="text" value="input something"/>
Submit: <input type="submit" value="Submit"/>
</form>