i open a spreadsheet and i can see in console:
_clipBoardOptions: "All"
in activeSheet obj.
but whenever i try to paste formatting from excel it just passes the value.
any thoughts on were i'm going wrong.?
Basically the default is "All" but no formatting is passed to SpreadJS
Here's my initialisation
$("#ss").wijspread({sheetCount:1}); // create wijspread control
var spread = $("#ss").wijspread("spread"); // get instance of wijspread control
var sheet = spread.getActiveSheet();
also when i try manually adding the method after the initialisation as so :
sheet.clipBoardOptions($.wijmo.wijspread.ClipboardPasteOptions[0])
i tried looking for a solution but not much information is giving and the api is kinda bum !
thanks in advance to any of you helpers!
SpreadJS does not support pasting formatting from Excel. We are looking into ways that we can implement support for that in a future release.
For now, SpreadJS can only import the entire Excel workbook using the ExcelIO web service.
To get the content of a cell range copied to SpreadJS, the best suggestion I have now is to use ExcelIO to import that workbook to a hidden SpreadJS instance, then use ClipboardPasteUndoAction to copy and paste the range from the hidden SpreadJS to the visible one.
Here is a code example showing how to use the ExcelIO web service to import an Excel file:
<!DOCTYPE html>
<html>
<head>
<title>Excel IO Sample</title>
<link type="text/css" href="./css/cobalt/jquery-wijmo.css" rel="stylesheet" />
<link type="text/css" href="./css/gcspread.sheets.8.40.20151.0.css" rel="stylesheet" />
<script type="text/javascript" src="./external/jquery-1.9.1.js"></script>
<script type="text/javascript" src="./scripts/gcspread.sheets.all.8.40.20151.0.min.js"></script>
<script type="text/javascript">
$(function () {
//Initialize SpreadJS
new GcSpread.Sheets.Spread($("#ss").get(0), {sheetCount: 2});
//For Excel Import
$("#btn_Import").click(function () {
// SpreadJS Excel IO import service api.
var serverUrl = $("#serviceHost").val() + "/xsapi/import";
// Generate import api options
var formData = new FormData();
//Choose a file to import
var $importingFile = $("#loadExcel");
var theFile = $importingFile[0].files[0];
var accept = "application/json";
formData.append("file", theFile);
formData.append("ExcelOpenFlags", "NoFlagsSet");
formData.append("TextFileOpenFlags", "None");
formData.append("Password", "");
$.ajax({
//Server script to process data
url: serverUrl,
type: 'POST',
//Ajax events
success: function completeHandler(data, textStatus, jqXHR) {
var spread = $("#ss").data("spread");
spread.fromJSON(JSON.parse(jqXHR.responseText).spread);
},
error: function errorHandler(jqXHR, textStatus, errorThrown) {
alert(errorThrown);
},
// Form data
data: formData,
//Options to tell jQuery not to process data or worry about content-type.
cache: false,
contentType: false,
processData: false,
//Options to tell server return data with specified type
headers: {
"Accept": accept
}
});
});
//For Excel Export with Form Post.
$("#btn_Export").click(function () {
var spread = $("#ss").data("spread");
// SpreadJS Excel IO import service api.
var serverUrl = $("#serviceHost").val() + "/xsapi/export";
// Generate import api options
var optContentType = "application/json";
// Post the json from spreadjs.
var dataObj = {
"spread": spread.toJSON(),
"exportFileType": "xlsx",
"excel": {
"saveFlags": "NoFlagsSet",
"password": ""
},
};
var content = JSON.stringify(dataObj);
var formInnerHtml = '<input type="hidden" name="type" value="' + htmlSpecialCharsEntityEncode(optContentType) + '" />';
formInnerHtml += '<input type="hidden" name="data" value="' + htmlSpecialCharsEntityEncode(content) + '" />';
var $iframe = $("<iframe style='display: none' src='about:blank'></iframe>").appendTo("body");
$iframe.ready(function () {
var formDoc = getiframeDocument($iframe);
formDoc.write("<html><head></head><body><form method='Post' action='" + serverUrl + "'>" + formInnerHtml + "</form>dummy windows for postback</body></html>");
var $form = $(formDoc).find('form');
$form.submit();
});
});
});
//gets an iframes document in a cross browser compatible manner
function getiframeDocument($iframe) {
var iframeDoc = $iframe[0].contentWindow || $iframe[0].contentDocument;
if (iframeDoc.document) {
iframeDoc = iframeDoc.document;
}
return iframeDoc;
}
var htmlSpecialCharsRegEx = /[<>&\r\n"']/gm;
var htmlSpecialCharsPlaceHolders = {
'<': 'lt;',
'>': 'gt;',
'&': 'amp;',
'\r': "#13;",
'\n': "#10;",
'"': 'quot;',
"'": 'apos;' /*single quotes just to be safe*/
};
function htmlSpecialCharsEntityEncode(str) {
return str.replace(htmlSpecialCharsRegEx, function (match) {
return '&' + htmlSpecialCharsPlaceHolders[match];
});
}
</script>
</head>
<body>
<h2>SpreadJS Excel IO Sample</h2>
<div style="margin-bottom: 10px">
<label><b>Excel IO Service Host : </b></label>
<input id="serviceHost" value="http://localhost/ExcelIO" style="width: 500px" />
</div>
<div id="ss" style="width: 660px; height: 500px; border: 1px solid gray; float: left">
</div>
<div style="width: 30%; height: 500px; margin-left: 15px; float: left">
<fieldset style="margin-bottom: 15px; height: 45%">
<legend><b>Excel IO Import Options</b></legend>
<input type="file" id="loadExcel" accept=".xlsx, .xls, .csv, .txt" />
<input id="btn_Import" type="button" value="Import" />
</fieldset>
<fieldset style="margin-bottom: 15px; height: 45%">
<legend><b>Excel IO Export Options</b></legend>
<input id="btn_Export" type="button" value="Export" />
</fieldset>
</div>
</body>
</html>
link: http://sphelp.grapecity.com/webhelp/SpreadJSWeb/webframe.html#exceliocode.html
Here is a code example showing how to use the ClipboardPasteUndoAction:
$(document).ready(function () {
//There are two buttons in html page with the id "cutPasteBtn" and "copyPasteBtn".
var spread = new GcSpread.Sheets.Spread($("#ss").get(0),{sheetCount:3});
var sheet = spread.getActiveSheet();
sheet.setValue(0, 0, 1, GcSpread.Sheets.SheetArea.viewport);
sheet.setValue(1, 0, 2, GcSpread.Sheets.SheetArea.viewport);
sheet.setFormula(2, 0, "=A1+A2", GcSpread.Sheets.SheetArea.viewport);
sheet.setValue(0, 1, 3, GcSpread.Sheets.SheetArea.viewport);
sheet.setValue(1, 1, 4, GcSpread.Sheets.SheetArea.viewport);
sheet.setFormula(2, 1, "=B1+B2", GcSpread.Sheets.SheetArea.viewport);
var fromRange = new GcSpread.Sheets.Range(0, 0, 3, 2);
var toRanges = [new GcSpread.Sheets.Range(4, 0, 3, 2)];
$("#cutPasteBtn").click(function () {
//Cut Paste Action
var clipboardCutPasteAction = new GcSpread.Sheets.UndoRedo.ClipboardPasteUndoAction(sheet, sheet, sheet, { fromRange: fromRange, pastedRanges: toRanges, isCutting: true, clipboardText: "" }, GcSpread.Sheets.ClipboardPasteOptions.Values);
clipboardCutPasteAction.execute(sheet);
});
$("#copyPasteBtn").click(function () {
//Copy Paste Action
var clipboardCopyPasteAction = new GcSpread.Sheets.UndoRedo.ClipboardPasteUndoAction(sheet, sheet, sheet, { fromRange: fromRange, pastedRanges: toRanges, isCutting: false, clipboardText: "" }, GcSpread.Sheets.ClipboardPasteOptions.Values);
clipboardCopyPasteAction.execute(sheet);
});
});
link: http://sphelp.grapecity.com/webhelp/SpreadJSWeb/webframe.html#sccopy.html
Regards,
GrapeCity Experts
Related
I am currently changing my system in order to have a loading progress bar when I now submit my form.
In my old system, I had this form and this script to check if the file exists and is in the right format:
Index.php
<form method="POST" enctype="multipart/form-data" id="myForm" action="upload.php">
<input type="file" name="imageSent" id="imgFile" class="inputImg" />
<label for="imgFile" class="labelForImgF">
<span>Select Img</span>
</label>
<button type="button" class="btnSubmit" onclick='verifyImg();'>
<span>Send</span>
</button>
</form>
<script>
function verifyImg() {
document.getElementById("warning").innerHTML = "";
var fileName = document.getElementById("imgFile");
if(fileName.files.item(0) == null) {
document.getElementById("warning").innerHTML = "You must select an img";
} else {
if(!isValidFileType(fileName.files.item(0).name,'image')) {
document.getElementById("warning").innerHTML = "Bad format";
} else {
document.getElementById('myForm').submit();
document.getElementById("warning").innerHTML = "Sucess";
}
}
}
var extensionLists = {};
extensionLists.image = ['jpg', 'nef', 'bmp', 'png', 'jpeg', 'svg', 'webp', '3fr', 'arw', 'crw', 'cr2', 'cr3', 'dng', 'kdc', 'mrw', 'nrw', 'orf', 'ptx', 'pef', 'raf', 'R3D', 'rw2', 'srw', 'x3f'];
function isValidFileType(fName, fType) {
return extensionLists[fType].indexOf(fName.toLowerCase().split('.').pop()) > -1;
}
</script>
And here is my new system, It works well with ajax but I can't check if the format is correct because as long as I put the onclick:verifyImg(); in my button the form submits without passing by the Ajax system.
Here is my new code:
<form method="POST" enctype="multipart/form-data" id="myForm" action="upload.php">
<input type="file" name="imageSent" id="imgFile" class="inputImg" />
<label for="imgFile" class="labelForImgF">
<span>Select Img</span>
</label>
<button class="btnSubmit">
<span>Send</span>
</button>
</form>
<div id="bararea">
<div id="bar"></div>
</div>
<div id="percent"></div>
<div id="status"></div>
<script>
$(function() {
$(document).ready(function(){
var bar = $('#bar')
var percent = $('#percent');
var status = $('#status');
$('form').ajaxForm({
beforeSend: function() {
status.empty();
var percentVal = '0%';
bar.width(percentVal);
percent.html(percentVal);
},
uploadProgress: function(event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
percent.html(percentVal);
bar.width(percentVal);
},
complete: function(xhr) {
status.html(xhr.responseText);
}
});
});
});
</script>
These two systems work well separately, but I can't mix them, in order to validate my form with javascript and submit it with Ajax.
I think I'm not understanding well how Ajax works, can you help me?
I am a beginner please be indulgent.
Solution:
I tried Chris G answer and changed the function beforeSend by beforeSubmit and now It works perfectly.
Code:
<form method="POST" enctype="multipart/form-data" id="myForm" action="upload.php">
<input type="file" name="imageSent" id="imgFile" class="inputImg" />
<label for="imgFile" class="labelForImgF">
<span>Select Img</span>
</label>
<button class="btnSubmit">
<span>Send</span>
</button>
</form>
<div id="bararea">
<div id="bar"></div>
</div>
<div id="percent"></div>
<div id="status"></div>
<script>
function verifyImg() {
document.getElementById("warning").innerHTML = "";
var fileName = document.getElementById("imgFile");
if(fileName.files.item(0) == null) {
document.getElementById("warning").innerHTML = "You must select an img";
return false;
} else {
if(!isValidFileType(fileName.files.item(0).name,'image')) {
document.getElementById("warning").innerHTML = "Bad format";
return false;
} else {
return true;
document.getElementById("warning").innerHTML = "Sucess";
}
}
}
var extensionLists = {};
extensionLists.image = ['jpg', 'nef', 'bmp', 'png', 'jpeg', 'svg', 'webp', '3fr', 'arw', 'crw', 'cr2', 'cr3', 'dng', 'kdc', 'mrw', 'nrw', 'orf', 'ptx', 'pef', 'raf', 'R3D', 'rw2', 'srw', 'x3f'];
function isValidFileType(fName, fType) {
return extensionLists[fType].indexOf(fName.toLowerCase().split('.').pop()) > -1;
}
</script>
<script>
$(document).ready(function(){
var bar = $('#bar')
var percent = $('#percent');
var status = $('#status');
$('form').ajaxForm({
beforeSubmit: function() {
if (!verifyImg()) return false ;
status.empty();
var percentVal = '0%';
bar.width(percentVal);
percent.html(percentVal);
},
uploadProgress: function(event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
percent.html(percentVal);
bar.width(percentVal);
},
complete: function(xhr) {
status.html(xhr.responseText);
}
});
});
</script>
use this code, I've check it, it runs well. If you want to test the upload progress, In google browser's console, select network→then select slow 3G here:
otherwise, you can't see the upload progress increase, you will see 100% in a flash unless you photo has a extremely big size.
user can't select non image file by adding accept attribute to the input box accept="image/*", even if not using this attribute, the javascript will validate the file format by there code, you can add other types here if you need "(jpeg|png|bmp)":
var file = $('input[name="photo"]').get(0).files[0];
var matchArr = file.type.match(/image\/(jpeg|png|bmp)/);
if (!matchArr) {
alert("file type not allow!");
return false;
}
This is the full code:
$(document).ready(function() {
$('input[type="button"]').on('click', function() {
var file = $('input[name="photo"]').get(0).files[0];
var matchArr = file.type.match(/image\/(jpeg|png|bmp)/);
if (!matchArr) {
alert("file type not allow!");
return false;
}
var words = $('input[name="words"]').val();
var formData = new FormData();
formData.append('photo', file);
formData.append('words', words);
$.ajax({
type: 'post',
url: '',
data: formData,
//contentType must be false(otherwise it will use default value:application/x-www-form-urlencoded; charset=UTF-8, which is wrong)
contentType: false,
//tell jquery don't process data(otherwise it will throw an error:Uncaught TypeError: Illegal invocation)
processData: false,
xhr: function() {
let xhr = new XMLHttpRequest();
//listening upload progress
xhr.upload.addEventListener('progress', function(e) {
if (e.lengthComputable) {
let progress = e.loaded / e.total;
progress = Math.round(progress * 10000) / 100 + '%';
$('.upload-progress').html(progress);
}
}, false);
return xhr;
},
success: function(response) {
console.log(response);
}
});
return false;
});
});
<html>
<head>
<title>AjaxFormDataUpload</title>
<meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport" />
<script src="http://apps.bdimg.com/libs/jquery/2.1.1/jquery.min.js"></script>
<style>
#upload-form {
width: 50%;
margin: 0 auto;
border: 1px solid blue;
}
.field {
padding: 10px;
}
.submit-btn {
text-align: center;
font-size: 20px;
}
</style>
</head>
<body>
<form id="upload-form">
<div class="field">
<input type="file" name="photo" accept="image/*">
<span class="upload-progress"></span>
</div>
<div class="field">
<input type="text" name="words">
</div>
<div class="submit-btn">
<input type="button" value="submit">
</div>
</form>
</body>
</html>
I try to import local image to Computer Vision API (OCR). But when I try to run it, it totally return nothing.
If I try to paste raw image into data: makeblob('') it work, but when I use variable from function get local image encodeImageFileAsURL(), it return nothing. I can get the raw image binary (base64), but when I try to take it into data to send to Cognitive services, it nothing happened.
function encodeImageFileAsURL() {
var filesSelected = document.getElementById("inputFileToLoad").files;
if (filesSelected.length > 0) {
var fileToLoad = filesSelected[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent) {
var srcData = fileLoadedEvent.target.result; // <--- data: base64
var newImage = document.createElement('img');
newImage.src = srcData;
document.getElementById("textBase64").innerHTML = srcData;
//alert("Converted Base64 version is " + document.getElementById("imgTest").innerHTML);
//console.log("Converted Base64 version is " + document.getElementById("imgTest").innerHTML);
}
fileReader.readAsDataURL(fileToLoad);
}
}
var a = document.getElementById("textBase64").value;
function processImage() {
// **********************************************
// *** Update or verify the following values. ***
// **********************************************
makeblob = function(dataURL) {
var BASE64_MARKER = ';base64,';
if (dataURL.indexOf(BASE64_MARKER) == -1) {
var parts = dataURL.split(',');
var contentType = parts[0].split(':')[1];
var raw = decodeURIComponent(parts[1]);
return new Blob([raw], {
type: contentType
});
}
var parts = dataURL.split(BASE64_MARKER);
var contentType = parts[0].split(':')[1];
var raw = window.atob(parts[1]);
var rawLength = raw.length;
var uInt8Array = new Uint8Array(rawLength);
for (var i = 0; i < rawLength; ++i) {
uInt8Array[i] = raw.charCodeAt(i);
}
return new Blob([uInt8Array], {
type: contentType
});
}
// Replace the subscriptionKey string value with your valid subscription key.
var subscriptionKey = "SORRY I CAN'T PUBLIC MY KEY";
// Replace or verify the region.
//
// You must use the same region in your REST API call as you used to obtain your subscription keys.
// For example, if you obtained your subscription keys from the westus region, replace
// "westcentralus" in the URI below with "westus".
//
// NOTE: Free trial subscription keys are generated in the westcentralus region, so if you are using
// a free trial subscription key, you should not need to change this region.
var uriBase = "https://southeastasia.api.cognitive.microsoft.com/vision/v1.0/ocr";
// Request parameters.
var params = {
"language": "unk",
"detectOrientation ": "true",
};
// Display the image.
var sourceImageUrl = document.getElementById("inputFileToLoad").value;
document.querySelector("#sourceImage").src = sourceImageUrl;
// Perform the REST API call.
$.ajax({
url: uriBase + "?" + $.param(params),
// Request headers.
beforeSend: function(jqXHR) {
jqXHR.setRequestHeader("Content-Type", "application/octet-stream");
jqXHR.setRequestHeader("Ocp-Apim-Subscription-Key", subscriptionKey);
},
type: "POST",
processData: false,
// Request body.
data: makeblob("'" + a + "'"),
})
.done(function(data) {
// Show formatted JSON on webpage.
$("#responseTextArea").val(JSON.stringify(data, null, 2));
})
.fail(function(jqXHR, textStatus, errorThrown) {
// Display error message.
var errorString = (errorThrown === "") ? "Error. " : errorThrown + " (" + jqXHR.status + "): ";
errorString += (jqXHR.responseText === "") ? "" : (jQuery.parseJSON(jqXHR.responseText).message) ?
jQuery.parseJSON(jqXHR.responseText).message : jQuery.parseJSON(jqXHR.responseText).error.message;
alert(errorString);
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Optical Character Recognition (OCR):</h1>
Enter the URL to an image of printed text, then click the <strong>Read image</strong> button.
<br><br>
<input id="inputFileToLoad" type="file" onchange="encodeImageFileAsURL();" />
<textarea rows="10" cols="60" id="textBase64"></textarea>
<br><br> Image to read: <input type="text" name="inputImage" id="inputImage" value="" />
<button onclick="processImage()">Read image</button>
<br><br>
<div id="wrapper" style="width:1020px; display:table;">
<div id="jsonOutput" style="width:600px; display:table-cell;">
Response:
<br><br>
<textarea id="responseTextArea" class="UIInput" style="width:580px; height:400px;"></textarea>
</div>
<div id="imageDiv" style="width:420px; display:table-cell;">
Source image:
<br><br>
<img id="imageTest" width="400" />
<div id="imageTest"></div>
</div>
</div>
<h1>Optical Character Recognition (OCR):</h1>
Enter the URL to an image of printed text, then click the <strong>Read image</strong> button.
<br><br>
<input id="inputFileToLoad" type="file" onchange="encodeImageFileAsURL();" />
<textarea rows="10" cols="60" id="textBase64"></textarea>
<br><br> Image to read: <input type="text" name="inputImage" id="inputImage" value="" />
<button onclick="processImage()">Read image</button>
<br><br>
<div id="wrapper" style="width:1020px; display:table;">
<div id="jsonOutput" style="width:600px; display:table-cell;">
Response:
<br><br>
<textarea id="responseTextArea" class="UIInput" style="width:580px; height:400px;"></textarea>
</div>
<div id="imageDiv" style="width:420px; display:table-cell;">
Source image:
<br><br>
<img id="imageTest" width="400" />
<div id="imageTest"></div>
</div>
</div>
Since a is already a string, you don't want to introduce the extra quotes when calling makeBlob because that will cause the atob call to fail. You want to simply say:
// Request body.
data: makeblob(a),
I am trying to insert multiple images in a single row in a field in oracle database, please suggest how to achieve it. Below are the details
image is rendering on the browser and I want to store multiple image through it in oracle db. Each image will have an id generating dynamically
aspx code:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<!DOCTYPE html>
<html>
<head>
<style>
input[type="file"] {
display:block;
}
.imageThumb {
max-height: 75px;
border: 2px solid;
margin: 10px 10px 0 0;
padding: 1px;
}
</style>
<title></title>
</head>
<body>
<form id="form1" runat="server">
Find the bellow HTML code
<h2>preview multiple images before upload using jQuery</h2>
<input type="file" id="files" name="files[]" multiple />
<asp:Button ID="Button3" runat="server" BorderColor="#CCFF66"
ForeColor="#0066FF" Text="Insert Data" />
</form>
<script src="http://code.jquery.com/jquery-1.11.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
var a = 0;
if (window.File && window.FileList && window.FileReader) {
$("#files").on("change", function (e) {
var files = e.target.files,
filesLength = files.length;
if (filesLength == 1) {
a = a + 1;
}
for (var i = 0; i < filesLength ; i++) {
var f = files[i]
var fileReader = new FileReader();
fileReader.onload = (function (e) {
var file = e.target;
$("<img></img>", {
class: "imageThumb",
Id: "img"+ a.toString(),
src: e.target.result,
title: file.name
}).insertAfter("#files");
});
fileReader.readAsDataURL(f);
}
});
} else { alert("Your browser doesn't support to File API") }
});
</script>
</body>
</html>
for saving image into oracle db I am using ajax and created webservice to push data into db:
[WebMethod]
public static void SaveUser(User user)
{
String connectionString = ConfigurationManager.ConnectionStrings["conndbprodnew"].ConnectionString;
using (OracleConnection con = new OracleConnection(connectionString))
{
using (OracleCommand cmd = new OracleCommand("INSERT INTO par_cinfo(Product_Id,IMAGETYPE ) VALUES (:IMAGETYPE )", con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("IMAGETYPE ", user.IMAGETYPE);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
}
public class User
{
public decimal Product_Id { get; set; }
public Image IMAGETYPE { get; set; }
}
jQuery ajax on button click to send data to webservices:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="http://cdn.jsdelivr.net/json2/0.1/json2.js"></script>
<script type="text/javascript">
$(function () {
$("[id*=Button3]").bind("click", function () {
var user = {};
user.Product_Id = 1;
user.IMAGETYPE= "here dynamic image id which is uploaded should be present "
$.ajax({
type: "POST",
url: "Default.aspx/SaveUser",
data: '{user: ' + JSON.stringify(user) + '}',
//data: JSON.stringify({user:user}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("User has been added successfully.");
window.location.reload();
}
});
return false;
});
});
</script>
The table which I created in oracle is as follows simply for entering the data in the table:
Create table par_cinfo
(
Product_Id NUMBER(10) NOT NULL PRIMARY KEY,
IMAGETYPE BLOB
)
I've managed to run the following code thanks to this post here Adding Microsoft's Emotion API to HTML website.
<HTML>
<head>
<title>JSSample</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<body>
<script type="text/javascript">
$(function() {
$.ajax({
url: "https://api.projectoxford.ai/emotion/v1.0/recognize",
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","my-key-here");
},
type: "POST",
// Request body
data: '{"url": "https://oxfordportal.blob.core.windows.net/emotion/recognition1.jpg"}',
})
.done(function(data) {
alert("success");
})
.fail(function(error) {
console.log(error.getAllResponseHeaders());
alert("fail");
});
});
</script>
</body>
</head>
</html>
This may seem like stupid question however I've been wondering how to get the emotions output from the HTML file? i.e. instead of the success alert I'd like to generate a text file which shows the output of the Emotions API with each emotion (like it does on their website).
One solution could be to read about Blob's. You could take the response from the ajax call in done() and create the text file you need. Here is an example for using Blob I found on JSFiddle:
var saveData = (function () {
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
return function (data, fileName) {
var json = JSON.stringify(data),
blob = new Blob([json], {type: "octet/stream"}),
url = window.URL.createObjectURL(blob);
a.href = url;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(url);
};
}());
var data = { x: 42, s: "hello, world", d: new Date() },
fileName = "my-download.json";
saveData(data, fileName);
source
data is an array, one item per face. If you just want to dump the text, you can call JSON.stringify(data). If you want pretty-print it in HTML, take a look at How can I pretty-print JSON using JavaScript?.
I've done this ins my website HowHappy.co.uk which is also on GitHub here: https://github.com/martinkearn/How-Happy
The way I displayed the data in a web site was to enumerate the array of faces in Javascript and use basic CSS to show the rectangle in the right place and Bootstrap popover to show the details data.
There is too much to put in this response so I recommend you look though the GitHub repo, but here are some of the key bits
Javascript
var dataString = JSON.stringify(response);
var data = JSON.parse(dataString);
//draw rectangle for each face
$.each(data.Faces, function (index, value) {
var rect = document.createElement('div');
rect.className = "rect";
rect.style.height = value.faceRectangle.height + "px";
rect.style.width = value.faceRectangle.width + "px";
rect.style.left = value.faceRectangle.left + "px";
rect.style.top = value.faceRectangle.top + "px";
rect.id = "rect" + index;
$('#result').append(rect);
//add popover
var popoverBody = "Happiness: " + Number((value.scores.happiness).toFixed(2))
+ "<br>Fear: " + Number((value.scores.fear).toFixed(2))
+ "<br>Anger: " + Number((value.scores.anger).toFixed(2))
+ "<br>Contempt: " + Number((value.scores.contempt).toFixed(2))
+ "<br>Disgust: " + Number((value.scores.disgust).toFixed(2))
+ "<br>Neutral: " + Number((value.scores.neutral).toFixed(2))
+ "<br>Sadness: " + Number((value.scores.sadness).toFixed(2))
+ "<br>Surprise: " + Number((value.scores.surprise).toFixed(2));
$('#rect' + index).popover({
title: (index + 1)
content: popoverBody,
html: "true",
trigger: "click"
});
});
Css
.rect {
position: absolute;
border-color: #FFEA0E;
border-style: solid;
border-width: 4px;
z-index: 10;
}
#result {
position: relative;
text-align: center;
margin: 0 auto;
width: auto;
}
#resultDetails {
font-size: 3rem;
text-align: center;
}
I use the library Highcharts in order to generate some graphics.
I would like to send them to the server and also to do a mysql request in order to save the data informations into my database. The thing is that It just download the file into my compuer.
I really would like to keep it on the server on a predefined folder. It just dowload it.
I wrote this code with many efforts.
I met many problems but I don't know how to pass this last.
Here is the code for generating the image and to download it auomatically:
<script type="text/javascript">//<![CDATA[
$(function(){
/**
* Create a global getSVG method that takes an array of charts as an argument
*/
Highcharts.getSVG = function(charts) {
var svgArr = [],
top = 0,
width = 0;
$.each(charts, function(i, chart) {
var svg = chart.getSVG();
svg = svg.replace('<svg', '<g transform="translate(0,' + top + ')" ');
svg = svg.replace('</svg>', '</g>');
top += chart.chartHeight;
width = Math.max(width, chart.chartWidth);
svgArr.push(svg);
});
return '<svg height="2400px" width="1200px" version="1.1" xmlns="http://www.w3.org/2000/svg">' + svgArr.join('') + '</svg>';
};
/**
* Create a global exportCharts method that takes an array of charts as an argument,
* and exporting options as the second argument
*/
Highcharts.exportCharts = function(charts, options) {
var form
svg = Highcharts.getSVG(charts);
// merge the options
options = Highcharts.merge(Highcharts.getOptions().exporting, options);
// create the form
form = Highcharts.createElement('form', {
method: 'post',
action: options.url
}, {
display: 'none'
}, document.body);
// add the values
Highcharts.each(['filename', 'type', 'width', 'svg'], function(name) {
Highcharts.createElement('input', {
type: 'hidden',
name: name,
value: {
filename: options.filename || 'chart',
type: options.type,
width: 1200,
svg: svg
}[name]
}, null, form);
});
//console.log(svg); return;
// submit
form.submit();
// clean up
form.parentNode.removeChild(form);
};
$('#export').click(function() {
Highcharts.exportCharts([chart1, chart2, chart3]);
});
});//]]>
</script>
</head>
<body>
<script src="js/highcharts.js"></script>
<script type="text/javascript" src="http://highcharts.com/js/testing-exporting.js"></script>
<div id="container" style="height: 400px; width:1200px"></div>
<div id="container2" style="height: 400px; width:1200px"></div>
<div id="container3" style="height: 400px; width:1200px"></div>
<button id="export">Export all</button>
I just try to send it to to server.
Thank you all verry much in advance for the help.
Receive my Utmost Respect.
Kind Regards SP.
you can try this
var chart = $('#yourchart').highcharts();
svg = chart.getSVG();
var base_image = new Image();
svg = "data:image/svg+xml,"+svg;
base_image.src = svg;
$('#mock').attr('src', svg);
var dataString = $('#mock').html() ; // or just binary code
$.ajax({
type: 'POST',
data: dataString,
url: 'your-server/',
success: function(data){
}
});
Save highchart as binary image