Tinimce 4 image upload throwing HTTP Error: 404 - javascript

I'm using tinymce 4 with image upload from example and after selecting picture to upload I'm getting "HTTP Error: 404" message.
I've tested example postAcceptor.php with posting image file and it works.
On result of posting image I'm getting that JSON response:
{"location":"/home/mylogin/domains/mydomain.com/public_html/projects/projectname/img/gallery/422.jpg"}
Is that correct with those extra slashes?
My code for init:
tinymce.init({
selector: 'textarea.content',
plugins: 'image code',
toolbar: 'undo redo | link image | code',
// enable title field in the Image dialog
image_title: true,
automatic_uploads: true,
images_upload_url: 'postAcceptor.php',
images_upload_base_path: '/img/gallery/',
images_upload_credentials: true,
file_picker_types: 'image',
// and here's our custom image picker
file_picker_callback: function(cb, value, meta) {
var input = document.createElement('input');
input.setAttribute('type', 'file');
input.setAttribute('accept', 'image/*');
input.onchange = function() {
var file = this.files[0];
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
var id = 'blobid' + (new Date()).getTime();
var blobCache = tinymce.activeEditor.editorUpload.blobCache;
var base64 = reader.result.split(',')[1];
var blobInfo = blobCache.create(id, file, base64);
blobCache.add(blobInfo);
cb(blobInfo.blobUri(), { title: file.name });
};
};
input.click();
}
});

The JSON you are returning sure looks like the location on the server's hard drive. The location gets turned into the src attribute for the image so it needs to be the URL that would allow the browser to fetch the image via the web server.

404 was caused because of
images_upload_url: 'postAcceptor.php',
I've changed it to
images_upload_url: './js/tinymce/postAcceptor.php',
Worked like a charm..

Related

How to export dataTable in .csv format?

Here What I am trying to do but not able to achieve the result.The data is getting downloaded without the '.csv' extension.
function get_modal1(data) {
$("#popupcontent").html(data);
var t = document.getElementById('tablename').innerText;
$('title').html(t);
$('#example').DataTable({
dom: 'lBfrtip',
buttons: [
'csv',
]
} );
this is how the data table is get exported without the extension .csv
I am not able to export the data as .csv. What I am doing wrong here?
The data is getting downloaded and when I open it with notepad it is comma separated.What could be the problem here?
[1]:
It's a bit of a rewrite but this is what I'd do, assuming your function is what will format the data and cause the file download:
function get_modal1(_data) {
// create a blob in memory of type text/csv
var _blob = new Blob([_data], {type: 'text/csv'});
var _file = "my_data.csv";
// create an anchor in memory for the file
var anc = document.createElement('a');
anc.style = "display: none";
// populate the url with the blob
var _f_url = window.URL.createObjectURL(blob);
anc.href = _f_url;
anc.download = _file;
// In case you have to support IE 11, IE 11 cannot handle dynamic click of an anchor to initiate save, so use msSaveBlob instead.
// in any case, fire the anchor link just created... user should get the file at this point.
if ( window.navigator.msSaveBlob ) {
window.navigator.msSaveBlob(blob, _file);
} else {
anc.dispatchEvent(new MouseEvent('click'));
}
// clear url out of memory to be safe.
window.URL.revokeObjectURL(_f_url);
});

Saving Image From HTML page To The NetSuite File Cabinet throw UNEXPECTED_ERROR

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();
}

Convert _body content (string) to an arrayBuffer

I have an Ionic application which downloads a file from a Web API. The content of the file can be found in the _body property of the HTTP response.
What I'm trying to do is convert this text into an arrayBuffer so I can save the content into a file.
However, the issue that I'm having is that any file (PDF files in my instance) that have images and/or large in size either don't show up at all or show up as correputed files.
At first I thought this was an issue relating Ionic. So to make sure I tried to simulate this issue and I was able to reproduce it.
Is this snippet you can select a PDF file, then download it. You would find that the downloaded file is corrupted and exactly how my Ionic app displays them.
HTML:
<input type="file" id="file_input" class="foo" />
<div id="output_field" class="foo"></div>
JS:
$(document).ready(function(){
$('#file_input').on('change', function(e){
readFile(this.files[0], function(e) {
//manipulate with result...
$('#output_field').text(e.target.result);
try {
var file = new Blob([e.target.result], { type: 'application/pdf;base64' });
var fileURL = window.URL.createObjectURL(file);
var seconds = new Date().getTime() / 1000;
var fileName = "cert" + parseInt(seconds) + ".pdf";
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
a.href = fileURL;
a.download = fileName;
a.click();
}
catch (err){
$('#output_field').text(err);
}
});
});
});
function readFile(file, callback){
var reader = new FileReader();
reader.onload = callback
//reader.readAsArrayBuffer(file);
reader.readAsText(file);
}
https://jsfiddle.net/68qeau3h/3/
Now, when using reader.readAsArrayBuffer(file); everything works as expected, however in my particular case, I used reader.readAsText(file); because this is how the data is retrieve for me, this is text form.
When adding these lines of code to try to convert the string into an arrayBuffer
...
var buf = new ArrayBuffer(e.target.result.length * 2); // 2 bytes for each char
var bufView = new Uint16Array(buf);
for (var i=0, strLen=e.target.result.length; i<strLen; i++) {
bufView[i] = e.target.result.charCodeAt(i);
}
var file = new Blob([buf], { type: 'application/pdf' });
...
This will not work and generate PDF files that the browser can't open.
So to recap, what I'm trying to do is somehow convert the result I get from reader.readAsText(file); to what reader.readAsArrayBuffer(file); produces. Because the files I'm working with, or the data im retrieving from my backend is this text form.

How do I fix orientation (upload image) before saving in folder (Javascript)?

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!

How to upload base64 image resource with dropzone?

I'm trying to upload generated client side documents (images for the moment) with Dropzone.js.
// .../init.js
var myDropzone = new Dropzone("form.dropzone", {
autoProcessQueue: true
});
Once the client have finished his job, he just have to click a save button which call the save function :
// .../save.js
function save(myDocument) {
var file = {
name: 'Test',
src: myDocument,
};
console.log(myDocument);
myDropzone.addFile(file);
}
The console.log() correctly return me the content of my document
data:image/png;base64,iVBORw0KGgoAAAANS...
At this point, we can see the progress bar uploading the document in the drop zone but the upload failed.
Here is my (standart dropzone) HTML form :
<form action="/upload" enctype="multipart/form-data" method="post" class="dropzone">
<div class="dz-default dz-message"><span>Drop files here to upload</span></div>
<div class="fallback">
<input name="file" type="file" />
</div>
</form>
I got a Symfony2 controller who receive the post request.
// Get request
$request = $this->get('request');
// Get files
$files = $request->files;
// Upload
$do = $service->upload($files);
Uploading from the dropzone (by drag and drop or click) is working and the uploads are successfull but using the myDropzone.addFile() function return me an empty object in my controller :
var_dump($files);
return
object(Symfony\Component\HttpFoundation\FileBag)#11 (1) {
["parameters":protected]=>
array(0) {
}
}
I think i don't setup correctly my var file in the save function.
I tryied to create JS image (var img = new Image() ...) but without any success.
Thanks for your help !
Finally i found a working solution without creating canvas :
function dataURItoBlob(dataURI) {
'use strict'
var byteString,
mimestring
if(dataURI.split(',')[0].indexOf('base64') !== -1 ) {
byteString = atob(dataURI.split(',')[1])
} else {
byteString = decodeURI(dataURI.split(',')[1])
}
mimestring = dataURI.split(',')[0].split(':')[1].split(';')[0]
var content = new Array();
for (var i = 0; i < byteString.length; i++) {
content[i] = byteString.charCodeAt(i)
}
return new Blob([new Uint8Array(content)], {type: mimestring});
}
And the save function :
function save(dataURI) {
var blob = dataURItoBlob(dataURI);
myDropzone.addFile(blob);
}
The file appears correctly in dropzone and is successfully uploaded.
I still have to work on the filename (my document is named "blob").
The dataURItoBlob function have been found here : Convert Data URI to File then append to FormData
[EDIT] : I finally wrote the function in dropzone to do this job. You can check it here : https://github.com/CasperArGh/dropzone
And you can use it like this :
var dataURI = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAmAAAAKwCAYAAA...';
myDropzone.addBlob(dataURI, 'test.png');
I can't comment currently and wanted to send this to you.
I know you found your answer, but I had some trouble using your Git code and reshaped it a little for my needs, but I am about 100% positive this will work for EVERY possible need to add a file or a blob or anything and be able to apply a name to it.
Dropzone.prototype.addFileName = function(file, name) {
file.name = name;
file.upload = {
progress: 0,
total: file.size,
bytesSent: 0
};
this.files.push(file);
file.status = Dropzone.ADDED;
this.emit("addedfile", file);
this._enqueueThumbnail(file);
return this.accept(file, (function(_this) {
return function(error) {
if (error) {
file.accepted = false;
_this._errorProcessing([file], error);
} else {
file.accepted = true;
if (_this.options.autoQueue) {
_this.enqueueFile(file);
}
}
return _this._updateMaxFilesReachedClass();
};
})(this));
};
If this is added to dropzone.js (I did just below the line with Dropzone.prototype.addFile = function(file) { potentially line 1110.
Works like a charm and used just the same as any other. myDropzone.addFileName(file,name)!
Hopefully someone finds this useful and doesn't need to recreate it!
1) You say that: "Once the client have finished his job, he just have to click a save button which call the save function:"
This implies that you set autoProcessQueue: false and intercept the button click, to execute the saveFile() function.
$("#submitButton").click(function(e) {
// let the event not bubble up
e.preventDefault();
e.stopPropagation();
// process the uploads
myDropzone.processQueue();
});
2) check form action
Check that your form action="/upload" is routed correctly to your SF controller & action.
3) Example Code
You may find a full example over at the official Wiki
4) Ok, thanks to your comments, i understood the question better:
"How can i save my base64 image resource with dropzone?"
You need to embedd the image content as value
// base64 data
var dataURL = canvas.toDataURL();
// insert the data into the form
document.getElementById('image').value = canvas.toDataURL('image/png');
//or jQ: $('#img').val(canvas.toDataURL("image/png"));
// trigger submit of the form
document.forms["form1"].submit();
You might run into trouble doing this and might need to set the "origin-clean" flag to "true". see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#security-with-canvas-elements
how to save html5 canvas to server

Categories

Resources