I have a function in my javascript file for downloading an annotated canvas and then moving it to the server.The rest of the jquery is working fine .. but for some reason these particular functions have stopped working.
$("#ContentPlaceHolder1_btnNext").click(function () {
var canvas = paper.project.activeLayer.view.element;
var img = $(canvas).parent().find('img')[0];
// var name = $("#ContentPlaceHolder1_Label9").text();
var name = $("#ContentPlaceHolder1_HiddenField1").val();
var mergeCanvas = $('<canvas>')
.attr({
width: $(img).width(),
height: $(img).height()
});
var mergedContext = mergeCanvas[0].getContext('2d');
mergedContext.clearRect(0, 0, $(img).width(), $(img).height());
mergedContext.drawImage(img, 0, 0);
mergedContext.drawImage(canvas, 0, 0);
//alert(canvas);
self.downloadCanvas(mergeCanvas[0], name);
//alert(mergeCanvas[0]);
//alert(name);
});
this.downloadCanvas = function (canvas, filename) {
/// create an "off-screen" anchor tag
var lnk = document.createElement('a'), e;
/// the key here is to set the download attribute of the a tag
lnk.download = filename;
/// convert canvas content to data-uri for link. When download
/// attribute is set the content pointed to by link will be
/// pushed as "download" in HTML5 capable browsers
lnk.href = canvas.toDataURL();
if (filename != "") {
/// create a "fake" click-event to trigger the download
if (document.createEvent) {
e = document.createEvent("MouseEvents");
e.initMouseEvent("click", true, true, window,
0, 0, 0, 0, 0, false, false, false,
false, 0, null);
lnk.dispatchEvent(e);
// save image to server
$.ajax({
type: 'POST',
url: 'home.aspx/MoveImages',
data: '{ "imageData" : "' + filename + '" }',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
//alert("Done, Picture Uploaded.");
}
});
It was working perfectly a month back .. But it has stopped working and I am not able to figure out what could have changed?
the following scripts are used :
<script type="text/javascript" src="https://code.jquery.com/jquery-
1.8.2.min.js"></script>
<script src="js/jquery-1.9.1.min.js" type="text/javascript"></script>
webmethod :
[System.Web.Services.WebMethod(EnableSession = true)]
public static void MoveImages(string imageData)
{
string fileName = "";
// get computer name
string clientMachineName;
clientMachineName = Dns.GetHostName();
string computerName = clientMachineName.Split('-').First();
// get download location
string pathUser = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
string sourcePath = Path.Combine(pathUser, "Downloads");
string pathstring = #"D:\........";
string class = HttpContext.Current.Session["class"].ToString().Trim();
string sub = HttpContext.Current.Session["subject"].ToString().Trim();
string targetPath = System.IO.Path.Combine(pathstring, class);
string pathstring1 = targetPath;
string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
string destFile = System.IO.Path.Combine(pathstring1, sub);
// Use Path class to manipulate file and directory paths.
if (System.IO.Directory.Exists(sourcePath))
{
string[] jpg = System.IO.Directory.GetFiles(sourcePath, "*.jpg");
string[] png = System.IO.Directory.GetFiles(sourcePath, "*.png");
string[] files = jpg.Concat(png).ToArray();
// Copy the files and overwrite destination files if they already exist.
foreach (string s in files)
{
// Use static Path methods to extract only the file name from the path.
if (s.Length > 0)
{
fileName = System.IO.Path.GetFileName(s);
sourceFile = Path.Combine(sourcePath, fileName);
//destFile = System.IO.Path.Combine(targetPath, fileName);
destFile = System.IO.Path.Combine(destFile, fileName);
if (File.Exists(destFile))
{
File.Delete(sourceFile);
}
else
{
System.IO.File.Move(s, destFile);
}
}
}
}
}
Background.js :
'use strict';
let disableShelf = () => chrome.downloads.setShelfEnabled(false);
chrome.runtime.onInstalled.addListener(disableShelf);
chrome.runtime.onStartup.addListener
(disableShelf);
Related
I'm trying to use the Upload Image CKEditor plugin link to upload pasted image in the ditor with a custom upload method, because I don't want to save the text with all the base6 image data, that make the data to save too long, and replace the data with the URL of the uploaded image.
I have a custom method that uploads the image and return a URL of a webmethod to call to get the image. In my custom upload method, I return a json object the the URL, , it works and uploads the image, but in the src attribute I still have the base64 data.
Ths is the CKEDitor configuration in my javascript file
CKEDITOR.replace('DESC_ARTICLEANSWER', {
language: editorlang,
toolbar: 'helpsi',
skin: 'moono',
filebrowserBrowseUrl: '/browser/browse.php',
filebrowserImageBrowseUrl: '/browser/browse.php?type=Images',
filebrowserUploadUrl: '../Common/uploadHandler.ashx?upload_type=img_ckeditor',
filebrowserImageUploadUrl: '../Common/uploadHandler.ashx?upload_type=img_ckeditor&CKEditorFuncNum=1&codeSiteId=' + $('#site').val()
});
And this is my custom method in uploadHandler.ashx file:
if ((context.Request.Form["upload_type"] == "img_ckeditor") || (context.Request.QueryString["upload_type"] == "img_ckeditor"))
{
string _atchHTML = ProcessImageCKEditor(context);
context.Response.Write(_atchHTML);
}
private string ProcessImageCKEditor(HttpContext context)
{
string _atchHTML = "";
try
{
string uploadpath = helpsi.framework.core.Configurator.Instance.getAppSettingsValue("APP_REQUEST_ATTACH_PATH");
if (!uploadpath.StartsWith("\\"))
{
uploadpath = context.Server.MapPath(uploadpath);
}
string file = context.Request.Files[0].FileName;
string ext = Path.GetExtension(file);
string fileName = Guid.NewGuid().ToString() + ext;
string filetoupload = Path.Combine(uploadpath, fileName);
HttpPostedFile uploads = context.Request.Files["upload"];
string CKEditorFuncNum = context.Request["CKEditorFuncNum"];
uploads.SaveAs(filetoupload);
string url = "../Common/GetAttachment.aspx?uploadedImage=1&FileName=" + fileName;
_atchHTML = "{\"uploaded\": 1, \"fileName\": \"" + fileName + "\", \"url\": \"" + url + "\"}";
}
catch (Exception ex)
{
_atchHTML = "ERROR:" + ex.Message;
}
return _atchHTML;
}
The upload method is called and it runs successfully, the image is saved, but when it returns, in the pasted image in the editor there is still the base64 data string, and not the url obtained with save. What am I missing?
In console I have this error, relative to the widget plugin.js file, in this function
function getFirstTextNode( el ) {
return el.find( function( node ) {
return node.type === 3;
}, true ).shift();
}
Uncaught TypeError: el.find is not a function
I have a suitelet that creates a html page. This page has a html element input type file. I am trying to take that file and upload it to the file cabinet. This is not done on a NetSuite form so the file element is not a netsuite file object.
The javascript on the HTML page is as follows
function uploadPhotoToNetSuite(){
var bookingid = $("#txtAddPhotoBookingId").val();
var caseid = $("#txtAddPhotoCaseId").val();
var isCase = caseid != "";
var base64Image = document.getElementById("imageToAdd").src;
var formData = new FormData();
formData.append("operations", 'uploadphoto');
formData.append("bookingid", bookingid);
formData.append("caseid", caseid);
formData.append("image", base64Image);
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4) {
var objResponse = JSON.parse(xhr.responseText);
if(!objResponse.uploadphoto.success){
alert(objResponse.uploadphoto.err);
} else {
closeLoading();
}
clearPhotoUpload();
}
};
xhr.open("POST", stAPIURL, true);
loading("Uploading Photo");
xhr.send(formData);
}
Then this matches to a method in my suitelet as follows.
function uploadPhoto(params, recUser){
try{
var imageFolder = 767406;
var thePhoto = params.image;
var filetype = "png";
if(thePhoto.indexOf("image/png") > -1) filetype = "png";
var theFile = file.create({
name: 'test.' + filetype,
fileType: filetype == "jpg" ? file.Type.JPGIMAGE : file.Type.PNGIMAGE,
contents: thePhoto,
description: 'This is a plain text file.',
encoding: file.Encoding.UTF8,
folder: imageFolder,
isOnline: true
});
var id = theFile.save();
} catch(err){
return {
success : false,
err : JSON.stringify(err)
}
}
return {
success : true
}
}
When this is happens I am getting the error UNEXPECTED_ERROR. The variable thePhoto is a base64 string of the image.
UPDATE:
I change the suitelet code to create a text file and the file uploaded perfectly and the base64 string was in the text file. When I took that base64 string and put it through a convertor, the image I uploaded was the result.
With this in mind, I changed the code again to;
var theFile = file.create({
name: 'test.jpg',
fileType: file.Type.JPGIMAGE,
contents: thePhoto,
description: 'This is a plain text file.',
encoding: file.Encoding.UTF8,
folder: imageFolder,
isOnline: true
});
And uploaded a .jpg file. Once again I got the error.
I was experiencing the same issue and finally figured out the resolution. NetSuite does convert Base64 image data to a JPEG file in the file cabinet automatically, but it can only be the raw base64 data. The base64 metadata at the beginning needs to be removed. After several hours of frustration, adding the first two lines to the function below allowed it to save properly as a JPEG file (without the unexpected error).
function saveJPEGFile(fileName, fileContents){
if (fileContents.startsWith('data:image/jpeg;base64'))
fileContents=fileContents.substring('data:image/jpeg;base64,'.length);
log.debug('saving file:',`${fileName} : ${fileContents.length} : ${fileContents}`)
var fileObj = file.create({
name : fileName,
fileType: file.Type.JPGIMAGE,
contents: fileContents,
folder : 1127
});
var fileId = fileObj.save();
}
I have a qr-code button. On click, qr-code is generated and dialog to save the image format pops-up. In which the filename always comes as "qrcode.png". I have to dynamically change the filename to the name of the files from where the qr-code is generated.
Please, help. I am new to this technology.
HTML TWIG
<th data-field="QR-BTN" data-width="60px" data-orderable="false">{{ 'QR'|trans }}</th>
JAVASCRIPT
var QREXPORT = (function() {
var qrCodeExport = function (e){
e.preventDefault();
//goqr.me api url
const QRCODE_API_URL = "https://api.qrserver.com/v1/create-qr-code/?"; //Library Used
var $form = $('#modal-qr-export-offering'),
qrFormat = $("input[name='qrCodeType']:checked").val(),
jsFormData = $form.data('bs.modal'),
accessCode = jsFormData.options.accesscode;
var params = {
data: "SESSION-" + accessCode,
size: "250x250",
margin: 0,
download: 1,
format: qrFormat,
};
window.location.href = QRCODE_API_URL + $.param(params);
};
return {
init: function() {
$(document).ready(function(){
$('#radioSvg').prop('checked', true);
$('#modal-qr-export-offering').on('hidden.bs.modal', function() {
location.reload();
});
});
$(document).on('click', '.js-btn-submit-form', qrCodeExport);
}
};
})();
QREXPORT.init();
Try using the a tag with download attribute...?
const linkEl = document.createElement('a')
linkEl.href = QRCODE_API_URL + $.param(params);
linkEl.download = 'download-name-here.png'
document.body.appendChild(linkEl)
linkEl.click()
// Maybe remove the link after it worked...?
linkEl.remove()
I try this reference : https://github.com/blueimp/JavaScript-Load-Image
I try like this : https://jsfiddle.net/oscar11/gazo3jc8/
My code javascript like this :
$(function () {
var result = $('#result')
var currentFile
function updateResults (img, data) {
var content
if (!(img.src || img instanceof HTMLCanvasElement)) {
content = $('<span>Loading image file failed</span>')
} else {
content = $('<a target="_blank">').append(img)
.attr('download', currentFile.name)
.attr('href', img.src || img.toDataURL())
var form = new FormData();
form.append('file', currentFile);
$.ajax({
url:'response_upload.php',
type:'POST',
data:form,
processData: false,
contentType: false,
success: function (response) {
console.log(response);
},
error: function () {
console.log(error)
},
});
}
result.children().replaceWith(content)
}
function displayImage (file, options) {
currentFile = file
if (!loadImage(
file,
updateResults,
options
)) {
result.children().replaceWith(
$('<span>' +
'Your browser does not support the URL or FileReader API.' +
'</span>')
)
}
}
function dropChangeHandler (e) {
e.preventDefault()
e = e.originalEvent
var target = e.dataTransfer || e.target
var file = target && target.files && target.files[0]
var options = {
maxWidth: result.width(),
canvas: true,
pixelRatio: window.devicePixelRatio,
downsamplingRatio: 0.5,
orientation: true
}
if (!file) {
return
}
displayImage(file, options)
}
// Hide URL/FileReader API requirement message in capable browsers:
if (window.createObjectURL || window.URL || window.webkitURL ||
window.FileReader) {
result.children().hide()
}
$('#file-input').on('change', dropChangeHandler)
})
If I uploaded the image, the image saved in the folder still does not use the image that is in its orientation set. I want when I upload a picture, the image stored in the folder is the image that has been set its orientation
It seems that the currentFile sent via ajax is the unmodified currentfFile. How do I get the modified currentFile?
After some researching little bit I found the solution thanks to this great plugin https://github.com/blueimp/JavaScript-Canvas-to-Blob . ( canvas-to-blob.js )
This plugin will convert your canvas to a Blob directly server would see it as if it were an actual file and will get the new(modified) file in you $_FILES array. All you need is call toBlob on the canvas object (img). After that you would get your blob which you then can send in FormData. Below is your updated updateResults() function
function updateResults (img, data) {
var content
if (!(img.src || img instanceof HTMLCanvasElement)) {
content = $('<span>Loading image file failed</span>')
}
else
{
content = $('<a target="_blank">').append(img)
.attr('download', currentFile.name)
.attr('href', img.src || img.toDataURL())
img.toBlob(
function (blob) {
var form = new FormData();
form.append('file', blob, currentFile.name);
$.ajax({
url:'response_upload.php',
type:'POST',
data:form,
processData: false,
contentType: false,
success: function (response) {
console.log(response);
},
error: function () {
console.log(error)
},
});
},'image/jpeg'
);
result.children().replaceWith(content);
}
}
You want to change some things about image (dimensions, roataion etc) and upload it on to the server but the problem here is that ImageLoad plugin will give the modified image as an canvas means it won't modify the original file selected in
<input type="file" id="file-input">. Since you are sending the file input object in form.append('file', currentFile); your modified file wont get sent but just the original
How to fix?
This is particularity hard you (or plugin) cannot modify anything on <input type="file" id="file-input"> due to browser restrictions neither you can send canvas directly to the server so the only way (used and works great) is to send the data URI of the image as a regular text and then decode it on the server, write it to a file.You might also want to send the original file name since a data URI is pure content and doesn't hold file name
Change
form.append('file', currentFile);
To
form.append('file', img.toDataURL() ); // data:image/png;base64,iVBO ...
form.append('file_name', currentFile.name ); // filename
PHP
$img_data=substr( $_POST['file'] , strpos( $_POST['file'] , "," )+1);
//removes preamble ( like data:image/png;base64,)
$img_name=$_POST['file_name'];
$decodedData=base64_decode($img_data);
$fp = fopen( $img_name , 'wb' );
fwrite($fp, $decodedData);
fclose($fp );
Good luck!
Using CKEditor to send email and upload attachments. Below is the minimal configuration I've from this source.
CKEDITOR.replace('email.Message', {
filebrowserUploadUrl: '/Controller/UploadAttachment',
extraPlugins: 'attach', // attachment plugin
toolbar: this.customToolbar, //use custom toolbar
autoCloseUpload: true, //autoClose attachment container on attachment upload
validateSize: 30, //30mb size limit
onAttachmentUpload: function(response) {
/*
the following code just utilizes the attachment upload response to generate
ticket-attachment on your page
*/
attachment_id = $(response).attr('data-id');
if (attachment_id) {
attachment = $(response).html();
$closeButton = $('<span class="attachment-close">').text('x').on('click', closeButtonEvent)
$('.ticket-attachment-container').show()
.append($('<div>', {
class: 'ticket-attachment'
}).html(attachment).append($closeButton))
.append($('<input>', {
type: 'hidden',
name: 'attachment_ids[]'
}).val(attachment_id));
}
}
});
On the Controller side I've got below code
const string scriptTag = "<script type='text/javascript'>window.parent.CKEDITOR.tools.callFunction({0}, '{1}', '{2}')</script>";
public ContentResult UploadAttachment()
{
string basePath = HttpContext.Server.MapPath("~/assets/Images/");
const string baseUrl = #"/ckfinder/userfiles/";
var funcNum = 0;
int.TryParse(Request["CKEditorFuncNum"], out funcNum);
if (Request.Files == null || Request.Files.Count < 1)
return BuildReturnScript(funcNum, null, "No file has been sent");
if (!System.IO.Directory.Exists(basePath))
return BuildReturnScript(funcNum, null, "basePath folder doesn't exist");
var receivedFile = Request.Files[0];
var fileName = receivedFile.FileName;
if (string.IsNullOrEmpty(fileName)) {
return BuildReturnScript(funcNum, null, "File name is empty");
}
var sFileName = System.IO.Path.GetFileName(fileName);
var nameWithFullPath = System.IO.Path.Combine(basePath, sFileName);
//Note: you may want to consider using your own naming convention for files, as this is vulnerable to overwrites
//e.g. at the moment if two users uploaded a file called image1.jpg, one would clash with the other.
//In the past, I've used Guid.NewGuid() combined with the file extension to ensure uniqueness.
receivedFile.SaveAs(nameWithFullPath);
var url = baseUrl + sFileName;
return BuildReturnScript(funcNum, url, null);
}
private ContentResult BuildReturnScript(int functionNumber, string url, string errorMessage) {
return Content(
string.Format(scriptTag, functionNumber, HttpUtility.JavaScriptStringEncode(url ? ? ""), HttpUtility.JavaScriptStringEncode(errorMessage ? ? "")),
"text/html"
);
}
Below is the response I get back inside onAttachmentUpload - function
<form enctype="multipart/form-data" method="POST" dir="ltr" lang="en" action="/Controller/UploadAttachment?CKEditor=email_Message&CKEditorFuncNum=0&langCode=en">
<label id="cke_73_label" for="cke_74_fileInput_input" style="display:none"></label>
<input style="width:100%" id="cke_74_fileInput_input" aria-labelledby="cke_73_label" type="file" name="attachment" size="38">
</form>
<script>
window.parent.CKEDITOR.tools.callFunction(98);
window.onbeforeunload = function({
window.parent.CKEDITOR.tools.callFunction(99)
});
</script>
But it is expecting some data-id for attachment id. I've no idea what the response should look like. Could someone tell me what the actual response should look like and what is the data-id its expecting as attr in response? Also, is there anyway I can upload multiple files with this?
This is how I am returning the response now and rendering the attached file. Hope it might help someone in future.
[AcceptVerbs(HttpVerbs.Post)]
public ContentResult UploadAttachment() {
string basePath = HttpContext.Server.MapPath("~/somepath");
var funcNum = 0;
int.TryParse(Request["CKEditorFuncNum"], out funcNum);
if (Request.Files == null || Request.Files.Count < 1)
return Content("No file has been sent");
if (!System.IO.Directory.Exists(basePath))
Directory.CreateDirectory(Path.Combine(basePath));
var receivedFile = Request.Files[0];
var fileName = receivedFile.FileName;
if (string.IsNullOrEmpty(fileName)) {
return Content("File name is empty");
}
var sFileName = System.IO.Path.GetFileName(fileName);
var nameWithFullPath = Path.Combine(basePath, sFileName);
receivedFile.SaveAs(nameWithFullPath);
var content = "<span data-href=\"" + nameWithFullPath + "\" data-id=\"" + funcNum + "\"><i class=\"fa fa-paperclip\"> </i> " + sFileName + "</span>";
return Content(content);
}
and on the JS side I have below code to append the uploaded file name:
CKEDITOR.replace('email.Message', {
filebrowserUploadUrl: '/Controller/UploadAttachment',
extraPlugins: 'attach', // attachment plugin
toolbar: this.customToolbar, //use custom toolbar
autoCloseUpload: true, //autoClose attachment container on attachment upload
validateSize: 30, //30mb size limit
onAttachmentUpload: function(response) {
/*
the following code just utilizes the attachment upload response to generate
ticket-attachment on your page
*/
attachment_id = $(response).attr('data-id');
if (attachment_id) {
attachment = response;
$closeButton = '<span class="attachment-close btn btn-danger float-right" style="margin-top:-7px"><i class="fa fa-trash"></i></span>'; //.on('click', closeButtonEvent)
$respDiv = '<ol class="breadcrumb navbar-breadcrumb" style="padding:18px 15px"><li style="display:block">' + attachment + $closeButton + '</li></ol>';
$('.ticket-attachment-container').show()
.append($('<div>', {
class: 'ticket-attachment'
}).html($respDiv))
.append($('<input>', {
type: 'hidden',
name: 'attachment_ids[]'
}).val(attachment_id));
$('.ticket-attachment-container').on('click', '.attachment-close', function() {
$(this).closest('.ticket-attachment').remove();
if (!$('.ticket-attachment-container .ticket-attachment').length)
$('.ticket-attachment-container').hide();
});
}
}
});