I want to take a screenshot of an HTML div tag when the web application is running on the client-side and store the image on the server. I read many articles on html2canvas and tried to implement the code however the image that is getting saved on the server is turning up all black. I tried by setting the background color to white but then it is turning up all white. In short, the image is blank. So any help will be appreciated. Thank you.
Html
<div id="viewer-container" class="sticky-top" style="height:70%;top:25%;width:41%;left:38%;">
<canvas id="viewer-canvas"></canvas>
</div>
Js
html2canvas(document.getElementById("viewer-container"), {
onrendered: function (canvas) {
var image = canvas.toDataURL("image/png");
image = image.replace('data:image/png;base64,', '');
$.ajax({
type: "POST",
url: '#Url.Action("TakeImage", "Home")',
data: { base64data: image },
success: function (result) { alert(result); }
});
}
})
Controller
[HttpPost]
public ActionResult TakeImage()
{
if (Request.Form["base64data"] != null)
{
string image = Request.Form["base64data"].ToString();
byte[] data = Convert.FromBase64String(image);
var path = Path.Combine(Server.MapPath("~/BIM"), "testimage.png");
System.IO.File.WriteAllBytes(path, data);
}
return View();
}
Related
I have a custom form on a SharePoint list in which the user uploads an image and a caption.
There is a PowerPoint slide with a template where the image should then go and the caption below it. Ideally I want the uploaded image to be taken from the SharePoint list and automatically input to the PowerPoint slide with the caption. The slide should then be saved as an image file and uploaded to SharePoint picture library to enable it to be used in a picture library slideshow on the homepage.
Does anyone have any idea how to do this or any other ways in which this may be possible.
I have tried using a combination of JavaScript and html with no luck.
You can use the SharePoint REST API to retrieve the image and caption from the SharePoint list, then use the Microsoft Graph API to add the image and caption to the PowerPoint slide template. Once the slide is updated, you can use the Microsoft Graph API to convert the slide to an image file and then upload the image file to the SharePoint picture library using the SharePoint REST API. You can use a programming language such as Python or JavaScript to automate this process.
You can refer to following code to upload pic to sharepoint by rest api and js
var fileInput = jQuery('#getFile');
var file = fileInput[0].files[0];
var serverRelativeUrlToFolder = '*****'; //if the library in subsite, You have to remove the forward slash "/" before the document library relative url.
proccessUploadUsingJQueryAjax(file, serverRelativeUrlToFolder);
function getFileBuffer(file) {
var deferred = jQuery.Deferred();
var reader = new FileReader();
reader.onloadend = function (e) {
deferred.resolve(e.target.result);
}
reader.onerror = function (e) {
deferred.reject(e.target.error);
}
reader.readAsArrayBuffer(file);
return deferred.promise();
}
function addFileToFolderUsingJQueryAjax(fileName, arrayBuffer, serverRelativeUrlToFolder) {
// Construct the endpoint.
var fileCollectionEndpoint = String.format(
"{0}/_api/web/GetFolderByServerRelativeUrl('{1}')/files/add(overwrite=true, url='{2}')",
_spPageContextInfo.webAbsoluteUrl, serverRelativeUrlToFolder, fileName);
// Send the request and return the response.
// This call returns the SharePoint file.
return jQuery.ajax({
url: fileCollectionEndpoint,
type: "POST",
data: arrayBuffer,
processData: false,
contentType: "application/json;odata=verbose",
headers: {
"accept": "application/json;odata=verbose",
"X-RequestDigest": jQuery("#__REQUESTDIGEST").val()
}
});
}
function proccessUploadUsingJQueryAjax(file, serverRelativeUrlToFolder){
var getFile = getFileBuffer(file);
getFile.done(function (arrayBuffer) {
// Add the file to the SharePoint folder.
var addFile = addFileToFolderUsingJQueryAjax("image.jpg", arrayBuffer, serverRelativeUrlToFolder);
addFile.done(function (file, status, xhr) {
alert("File Uploaded");
});
addFile.fail(function (error) { alert("Error Add File: " + error.responseText); });
});
getFile.fail(function (error) { alert("Error Get File: " + error.responseText); });
}
I am using Cropper.js to send a cropped image to a server, but when I use "convtoblob(blob )" and append blob to formfile then send it to web API, original image Filename miss and according to attached image change to "blob"!
Please help me!
Part of my code is shown below:
canvas.toBlob(function(blobs) {
//blobs.nam = FN;
var formData = new FormData();
formData.append("up", blobs);
$.ajax('http://localhost:51320/api/fileupload/uploadfile', {
method: 'POST',
processData: false,
contentType: false,
data: formData,
cache: false,
success: function(d) {
var d;
$alert.show().addClass('alert-success').text('Upload success');
},
error: function(d) {
var d;
avatar.src = initialAvatarURL;
$alert.show().addClass('alert-warning').text('Upload error');
},
complete: function(d) {
var d;
$progress.hide();
}
});
});
Even when I add a new property as you see "//blobs.nam = FN;" I don't get it in webAPI.
also i have got canvas-toBlob.js but any changes!
please help me!
web api print screen
html page print screen
You can append the formdata like this
formData.append('up', blobs, "blobs.jpg");
Third parameter is your file name.if you want to get your old file name please just read your input type="file" value like this
var yourFileName = $("#ImageFile").val().split('\\').pop(); and change the appending code to
formData.append('up', blobs, yourFileName );
it's tested and working fine.
i am working on a code for rest api in which i am at page "imageTest" wth a image and button "onclick event" of the button will call function "foo()"
#RequestMapping(value = "/imageUpload2/", method = RequestMethod.POST, produces = "application/json")
public ResponseEntity profilePicTest(#RequestBody String data) {
System.out.println("imageString length : " + data.length());
System.out.println("imageUpload : " + data);
return new ResponseEntity(null, HttpStatus.OK);
javascript part
function foo() {
alert('uploading image to imageupload2 url');
var profpic = document.getElementById("profpic");
alert('uploading image1122334455')
jQuery.ajax( {
url: 'http://localhost:8090/EventApp/imageUpload2/',
type: 'POST',
data: { img: profpic },
success: function( response ) {
// response
}
} ); alert('uploading done')
}
can anyone help me in the part were i can upload image by javascript (with encoding like base64) which restcontroller can accept that image string further convert into byte[] array and inserted into oracle db blob column and vice versa to send it back
------problem part----
image not uploading in json as string
please anyone help me ...!
The value of data should just be the file object from the input.
HTML
<input type="file" id="profpic" />
JS
var file = $("#profpic")[0].files[0];
jQuery.ajax( {
url: 'http://localhost:8090/EventApp/imageUpload2/',
type: 'POST',
data: file,
success: function( response ) {
// response
}
});
Note: This doesn't work in many older browsers. IE10+ is fine but anything older than that will require a different method.
I'm having difficulties saving my canvas. I'm new to javascript so I think it could be a syntax issue.
I've got some vars saved in a function:
var imageView = document.getElementById("imageView");
var canvasData = imageView.toDataURL("image/png");
var postData = "canvasData="+canvasData;
If I add the following line it displays the image correctly:
imgData = $('#i').append($('<img/>', { src : canvasData }));
However, I have another function that I want to pass the base64 code in so I added:
var the_data = "test= "+imageView.toDataURL("image/png");
It does print out a base64 code, but just the blank canvas (not with the drawing the user has added).
If I add the following it doesn't work:
var the_data = "test= "+canvasData;
What am I doing wrong?
This is a basic jsfiddle of what I'm trying to do: http://jsfiddle.net/sMSeX/
Just a little hint from my side for uploading HTML5 canvas image data:
I am working on a project for a print-shop and had some problems due to uploading images to the server that came from an HTML5 canvas element. I was struggling at least for one hour and I did not get it to save the image correctly on my server.
I get the image data as Base64 decoded from the canvas element via
var can = document.getElementsByTagName('canvas');
var dataURL = can[0].toDataURL("image/jpg");
//dataURL = dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
console.log('data url: '+dataURL);
Once I set the
contentType option of my jQuery ajax call to 'application/x-www-form-url-encoded' :
$.ajax({
url: 'index.php?page=upload-image',
type: 'post',
contentType: 'application/x-www-form-urlencoded',
//data: '{ "imageData" : "' + dataURL + '" }',
data: dataURL,
beforeSend: function() {
$('.text-danger').remove();
},
complete: function() {
},
success: function(json) {
console.log('upload complete');
}
});
everything went the right way and the base64-encoded data was interpreted correctly and successfully saved as an image.
Maybe someone helps that!
I need some help here..
Im trying to save a canvas image after drawing..
following this example (http://www.dotnetfunda.com/articles/article1662-saving-html-5-canvas-as-image-on-the-server-using-aspnet.aspx)
$("#btnSave").click(function () {
var image = document.getElementById("canvas").toDataURL("image/png");
image = image.replace('data:image/png;base64,', '');
$.ajax({
type: 'POST',
url: "../../Home/UploadImage?imageData=" + image,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
alert('Image saved successfully !');
}
});
});
the controller:
public void UploadImage(string imageData)
{
string fileNameWitPath = path + DateTime.Now.ToString().Replace("/", "-").Replace(" ", "- ").Replace(":", "") + ".png";
using (FileStream fs = new FileStream(fileNameWitPath, FileMode.Create))
{
using (BinaryWriter bw = new BinaryWriter(fs))
{
byte[] data = Convert.FromBase64String(imageData);
bw.Write(data);
bw.Close();
}
}
}
But when im trying to convert form base64 the string that is passed like parameter in method, throw an error
Invalid length for a character array Base-64.
You can't post data with querystring parameters
Try this;
$("#btnSave").click(function () {
var image = document.getElementById("canvas").toDataURL("image/png");
image = image.replace('data:image/png;base64,', '');
$.ajax({
type: 'POST',
url: "../../Home/UploadImage",
data: '{ "imageData" : "' + image + '" }',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
alert('Image saved successfully !');
}
});
});
In that example, the author has posted the image data using a hidden field, notice below line of code in his article
<input type="hidden" name="imageData" id="imageData" />
http://www.dotnetfunda.com/articles/show/2665/saving-html-5-canvas-as-image-in-aspnet-mvc
And on click of the button, he is submitting the form after getting canvas data to the hidden field so follow the same approach. As written by Mehmet, querystring has limitations and its prone to be modified as it goes via url.
Instead of this
image = image.replace('data:image/png;base64,', '');
use this:
image = image.substr(23, image.length);
remove the leading characters up to the first comma (use any dev tool to see what you posted).