Tinymce truncating 'https://localhost:5001' after resolve() - javascript

I use tinymce 6.1.0, I want to save absolute picture url after uploading, but I can't do this because tinymce truncated url and return relative url after resolve() executed, also tinymce doesn't truncated if I resolve('httpls://localhost:5001/'):
var editor = tinymce.init(
{
selector: '#UpdateViewModel_HtmlContent',
setup: function (editor)
{
editor.on('change', function ()
{
editor.save();
});
},
images_upload_handler: function (blobInfo, progress)
{
return new Promise((resolve, reject) =>
{
formData = new FormData();
formData.append(blobInfo.filename(), blobInfo.blob());
abp.ajax({
type: "POST",
url: abp.appPath + 'api/static/editing/content/image',
data: formData,
processData: false,
contentType: false,
success: function (res)
{
progress && progress(100);
resolve('https://localhost:5001/' + res.url);
},
error: function (err)
{
reject('Failed to upload image to server');
},
formData: "multipart/form-data"
});
});
},
plugins: 'image code',
toolbar: 'undo redo | link image | code',
file_picker_types: 'image'
});
How to change my code?

In init method I added this parameter:
convert_urls: false
This not work:
relative_urls: 0,
remove_script_host: 0

Related

Ext js 7 modern, form.submit vs ajax.request

I have a Ext.form.Panel with multiple textareafield and fileinput like this
// https://requestbin.com/r/en0ej96odon2sm/1n6r1tb49KK6eObGMPHlYa1hh4C
Ext.create({
xtype: 'formpanel',
renderTo: document.body,
buttons: {
submit: 'onSubmit',
},
controller: {
onSubmit: function () {
var form = this.getView();
form.submit({
method: 'POST',
url: 'https://en0ej96odon2sm.x.pipedream.net/test1',
success: function () {}
});
},
onSubmitTest: function () {
var form = this.getView();
Ext.Ajax.request({
url: 'https://en0ej96odon2sm.x.pipedream.net/test2',
method: 'POST',
params: {
data: form.getValues(),
},
success: function () {}
});
},
},
items: [{
xtype: 'textareafield',
name: 'testfield',
label: 'testfield',
value: 'test\nasd',
}, {
xtype: 'filefield',
label: 'Upload Test',
name: 'basedata-test',
}, {
xtype: 'button',
text: 'Ajax.request(), linebreaks but no files',
handler: 'onSubmitTest',
}]
});
Post Results:
https://requestbin.com/r/en0ej96odon2sm/1n6mtu8QtyreaisCAmV3csO724Q
Fiddle:
https://fiddle.sencha.com/#view/editor&fiddle/3b9j
So, cause i need fileinput/multipart, I have to use form.submit({}).
But when I do so, I don't get the linebreaks on Server side in my $_POST Var.
When I do a ajax.request({}) everything looks good, but $_FILES are missing, so this is not really an option. (but this is documented).
I also tried adding jsonSubmit to the form (then I get no $_POST at all).
When I add enableSubmissionForm: false I get the newline, but after submit the form disappears (and I don't know why).
Is there a solution for this or am I doing something wrong?
You can use the following override. Hope it will not make the framework unstable ;)
// https://requestbin.com/r/en0ej96odon2sm/1n6r1tb49KK6eObGMPHlYa1hh4C
// Override
Ext.define('overrides.form.Panel', {
override: 'Ext.form.Panel',
privates: {
createSubmissionForm: function (form, values) {
var fields = this.getFields(),
name, input, field, fileTrigger, inputDom;
if (form.nodeType === 1) {
form = form.cloneNode(false);
for (name in values) {
input = document.createElement('textarea');
input.setAttribute('type', 'string');
input.setAttribute('name', name);
input.innerHTML = values[name];
form.appendChild(input);
}
}
for (name in fields) {
if (fields.hasOwnProperty(name)) {
field = fields[name];
if (field.isFile) {
// The <input type="file"> of a FileField is its "file" trigger button.
fileTrigger = field.getTriggers().file;
inputDom = fileTrigger && fileTrigger.getComponent().buttonElement.dom;
if (inputDom) {
if (!form.$fileswap) {
form.$fileswap = [];
}
input = inputDom.cloneNode(true);
inputDom.parentNode.insertBefore(input, inputDom.nextSibling);
form.appendChild(inputDom);
form.$fileswap.push({
original: inputDom,
placeholder: input
});
}
} else if (field.isPassword) {
if (field.getInputType() !== 'password') {
field.setRevealed(false);
}
}
}
}
return form;
}
}
});
Ext.create({
xtype: 'formpanel',
renderTo: document.body,
buttons: {
submit: 'onSubmit',
},
controller: {
onSubmit: function () {
var form = this.getView();
form.submit({
method: 'POST',
url: 'https://en0ej96odon2sm.x.pipedream.net/test1',
success: function () {}
});
},
onSubmitTest: function () {
var form = this.getView();
Ext.Ajax.request({
url: 'https://en0ej96odon2sm.x.pipedream.net/test2',
method: 'POST',
params: {
data: form.getValues(),
},
success: function () {}
});
},
},
items: [{
xtype: 'textareafield',
name: 'testfield',
label: 'testfield',
value: 'test\nasd',
}, {
xtype: 'filefield',
label: 'Upload Test',
name: 'basedata-test',
}, {
xtype: 'button',
text: 'Ajax.request(), linebreaks but no files',
handler: 'onSubmitTest',
}]
});
Not ideal, but you also can do this:
form.submit({
method: 'POST',
//just like the ajax
params: {
data: form.getValues(),
},
url: 'https://en0ej96odon2sm.x.pipedream.net/test1',
success: function () {}
});
Here is a simple workaround for using Ajax.request instead of form.submit
I needed that because I have to set an Authorization header, which can't be done with IFRAME used by the framework
So preventing Ext.data.request.Ajax from setting Content-Type header seems to do the job.
multipart/form-data will be automatically set.
Warning : neither options.headers nor defaultHeaders should already have the 'Content-Type' header
Ext.define('Override.data.request.Ajax', {
override: 'Ext.data.request.Ajax',
setupHeaders: function(xhr, options, data, params) {
if (data instanceof FormData) {
if (Ext.apply({}, options.headers || {}, this.defaultHeaders).hasOwnProperty('Content-Type')) {
console.warn('The Content-Type header must not be set before request if you need to use FormData with this override');
}
/* prevent Ext.data.request.Ajax from setting Content-Type header */
return this.callParent([xhr, options, null, null]);
} else {
return this.callParent(arguments);
}
}
});
And call Ajax.request with a FormData as rawData
var formData = new FormData();
var files = myView.down('filefield').getFiles();
if (files.length > 0) {
formData.append('file', files[0], files[0].name);
}
Ext.Ajax.request({
url: 'your_url',
rawData: formData,
success: function(response) {
// handle success
},
failure: function(response) {
// handle failure
}
});

how to add cloudinary parameters to upload plugin in Trumbowyg

I am using the trumbowyg editor in my project. From the documentation, I know that I can use the following code to set the image upload content of the editor.
$('#editor')
.trumbowyg({
btns: ['upload'],
plugins: {
// Add imagur parameters to upload plugin for demo purposes
upload: {
serverPath: 'https://api.imgur.com/3/image',
fileFieldName: 'image',
headers: {
'Authorization': 'Client-ID xxxxxxxxxxxx'
},
urlPropertyName: 'data.link'
}
}
});
this works fine with imgur but I want to use cloudinary server instead of imgur.
could anyone please guide what I have to do with plugins:{} when using cloudinary?
also I'm using dropzone.js with cloudinary to upload image and this is also working properly.
here is dropzone function code:
Dropzone.autoDiscover = true;
var myDropzone = new Dropzone(document.getElementById('image-upload'), {
clickable: "#image-upload #btn-add",
uploadMultiple: false,
autoProcessQueue: true,
acceptedFiles:'.jpg,.png,.jpeg,.gif',
parallelUploads: 10,
maxFilesize: 9,
maxFiles: 10,
url: 'https://api.cloudinary.com/v1_1/demo_project/image/upload',
addedfile: function(file) {
// console.log(file);
new Noty({
type: 'success',
text: "Uploading...",
timeout: false
}).show();
// myDropzone.processQueue();
},
success: function(file, response){
new Noty({
type: 'success',
text: "Uploaded!",
killer: true
}).show();
newImageArray.push({
public_id: response.public_id,
url: response.url,
secure_url: response.secure_url
});
newImageArrayJSON = JSON.stringify(newImageArray);
$imageStorage.val(newImageArrayJSON)
$("#image-upload .image").html('<img src="' + response.secure_url + '">')
$("#image-upload #btn-add").hide();
$("#image-upload #btn-remove").show();
}
});
myDropzone.on('sending', function (file, xhr, formData) {
formData.append('api_key', 112233445566778);
formData.append('timestamp', Date.now() / 1000 | 0);
formData.append('upload_preset', 'mypreset');
});
Thanks in advance!
I would advise starting with the following basic implementation which I tested and worked for me:
$('#editor').trumbowyg({
btns: ['upload'],
plugins: {
upload: {
serverPath: 'https://api.cloudinary.com/v1_1/demo_project/image/upload',
fileFieldName: 'file',
urlPropertyName: 'data.secure_url',
data: [
{name: 'api_key', value: '112233445566778'},
{name: 'timestamp', value: Date.now() / 1000 | 0},
{name: 'upload_preset', value: 'mypreset'}
],
success: function (data) {
console.log(data);
},
error: function (error) {
console.log(error.responseText);
}
}
}
});
You can log in to your Cloudinary account and modify your upload preset to restrict uploads based on different conditions, the same as you do with dropzone.js, for example to only allow uploads of specific formats etc.

Preprocess before kendo ui upload

I want to pass some data(a guid) to the upload method of the kendoUpload so that the particular MVC Controller action method will receive that data. Each time the upload happens, I need to pass this data (guid).
$("#propertyAttachmentUpload").kendoUpload({
async: {
saveUrl: fileUploadUrl,
chunkSize: 1048576,
removeUrl: "remove"
},
multiple: true,
upload: function (e) {
e.data = { id: $("#fileUplpderParentObjectId").val(), fileId: fileId };
},
showFileList: false,
dropZone: ".propertyAttachmentDropZone",
success: onSuccess
});
The field is fileId. I can call the above code block in a click event of the upload button and it works but the Kendo UI styles are not applied to the upload button at the initialization.
$("#propertyAttachmentUpload").click(
function() {
var fileId = guid();
$("#propertyAttachmentUpload").kendoUpload({
async: {
saveUrl: fileUploadUrl,
chunkSize: 1048576,
removeUrl: "remove"
},
multiple: true,
upload: function (e) {
e.data = { id: $("#fileUplpderParentObjectId").val(), fileId: fileId };
},
showFileList: false,
dropZone: ".propertyAttachmentDropZone",
success: onSuccess
});
});
How can I initialize the fileId without loosing the Kendo UI styles.
Note: I cannot call guid() inside upload method since the upload method calls for each uploading chunk. For all the chunks the fileId should be same for a particular file.
I've resolved this problem using a global variable and setting that variable in the click event of the upload button,
var fileGuid = '';
$(document).on('click', '#propertyAttachmentUpload', function() {
fileGuid = "";
fileGuid = guid();
})
$("#propertyAttachmentUpload").kendoUpload({
async: {
saveUrl: fileUploadUrl,
chunkSize: 1048576,
removeUrl: "remove"
},
multiple: true,
upload: function (e) {
e.data = { id: $("#fileUplpderParentObjectId").val(), fileId: fileGuid };
},
showFileList: false,
dropZone: ".propertyAttachmentDropZone",
success: onSuccess
});

Why fail to call method in vue component if collaborate with a plugin?

I get reference to fix orientation image from here :
https://github.com/blueimp/JavaScript-Canvas-to-Blob
I try in vue component like this :
<template>
<div>
...
</div>
</template>
<script>
export default {
...
methods: {
...
changeImage(item, $event) {
...
loadImage(
$event.target.files[0],
function (img) {
img.toBlob(
function (blob) {
// create a form
const form = new FormData();
form.append('file', blob, $event.target.files[0].name);
// define the done handler
const onDone = (response) => {
if (!$.trim(response)) {
alert('No response');
}
else {
const files = $event.target.files || $event.dataTransfer.files
if (!files.length)
return;
this.createImage(item, response)
...
}
}
// define th post options
const options = {
url: window.Laravel.baseUrl+'/product/addImageTemp',
type: "POST",
data: form,
enctype: 'multipart/form-data',
processData: false, // tell jQuery not to process the data
contentType: false // tell jQuery not to set contentType
}
// submit the image
$.ajax(options).done(onDone);
}, $event.target.files[0].type
);
},
{
maxWidth: 600,
canvas: true,
pixelRatio: window.devicePixelRatio,
downsamplingRatio: 0.5,
orientation: true
} // Options
);
},
createImage(item, response) {
...
}
}
}
</script>
It works. It success upload image in folder. But on the console exist error :
Uncaught TypeError: Cannot read property 'createImage' of undefined
The error here : this.createImage(item, response)
Seems the error because it cannot use this in function (img) {
How can I solve this problem?
I need this plugin to fix orientation image
Capture the current this at the beginning of the method and use it to call the createImage method:
methods:{
changeImage(item, $event) {
const self = this
loadImage($event.target.files[0], function(img){
...
self.createImage(...)
...
})
}
}

Images upload to folder in Summernote editor

I have asp.net mvc 4 application. In that application I have form , in that form I have summernote rich text editor. But in this editor I have option to upload images to this editor.
But Once I fill rest of the fields and sumbit the this form. Its not saving images that I uploaded through summernote editor .
I want to upload images to following path ~/Content/Images/
and keep the path as ~/Content/Images/Image_Name.JPG in database field
So I tried to create my solution as following by following this solution and GitHub Issue reported here
from Viewpage
<div class="form-group">
#Html.TextAreaFor(m => m.Field_Value, new { #class = "form-control summernote"})
</div>
Controller method
[HttpPost]
public byte[] UploadImage(HttpPostedFileBase file)
{
Stream fileStream = file.InputStream;
var mStreamer = new MemoryStream();
mStreamer.SetLength(fileStream.Length);
fileStream.Read(mStreamer.GetBuffer(), 0, (int)fileStream.Length);
mStreamer.Seek(0, SeekOrigin.Begin);
byte[] fileBytes = mStreamer.GetBuffer();
Stream stream = new MemoryStream(fileBytes);
//string result = System.Text.Encoding.UTF8.GetString(fileBytes);
var img = Bitmap.FromStream(stream);
Directory.CreateDirectory("~//Content//Images//" + img);
return fileBytes;
}
this is script
<script type="text/javascript">
$('.summernote').summernote({
height: 200, // set editable area's height
focus: true, // set focus editable area after Initialize summernote
onImageUpload: function (files, editor, welEditable) {
var formData = new FormData();
formData.append("file", files[0]);
$.ajax({
url: "#Url.Action("Home", "UploadImage")",
data: formData,
type: 'POST',
cache: false,
contentType: false,
processData: false,
success: function (imageUrl) {
if (!imageUrl) {
debugger;
// handle error
return;
}
editor.insertImage($editable, imageUrl);
},
error: function () {
// handle error
}
});
}
});
this once also, its not showing whether image uploaded to editor at all
I updated your script, and it works for me (check the changes on code comments):
<script type="text/javascript">
var editor = // 1st change: will need this variable later
$('.summernote').summernote({
height: 200,
focus: true,
callbacks: { // 2nd change - onImageUpload inside of "callbacks"
onImageUpload: function (files) { // 3rd change - dont need other params
var formData = new FormData();
formData.append("file", files[0]);
$.ajax({
url: "#Url.Action("Home", "UploadImage")",
data: formData,
type: 'POST',
cache: false,
contentType: false,
processData: false,
success: function (imageUrl) {
if (!imageUrl) {
// handle error
return;
}
// 4th change - create img element and add to document
var imgNode = document.createElement('img');
imgNode.src = imageUrl;
editor.summernote('insertNode', imgNode);
},
error: function () {
// handle error
}
});
}
}
});
</script>

Categories

Resources