Hello im new'ish in using and editing api's and im a bit stumped on TUI's Image Editor.
I'm trying to get the image data as a variable so that I can upload it separately to a website instead of just downloading it to the computer.
I am using this person's version of tui. I tried other methods as well but they didn't quite worked out for me.
const imageEditor = new tui.ImageEditor('#tui-image-editor-container', {
includeUI: {
loadImage: {
path: 'img/sampleImage2.png',
name: 'SampleImage',
},
theme: blackTheme, // or whiteTheme
initMenu: 'filter',
menuBarPosition: 'bottom',
},
cssMaxWidth: 700,
cssMaxHeight: 500,
usageStatistics: false,
});
window.onresize = function () {
imageEditor.ui.resizeEditor();
}
document.querySelector('#downloadButton').addEventListener('click', () => {
const myImage = instance.toDataURL();
document.getElementById("url").innerHTML = myImage;
});
</script>
<p id="url">Test</p>
Tried to change the code by using other guides but now it shows this error
Changed code
var imageEditor = new tui.ImageEditor('#tui-image-editor-container', {
includeUI: {
loadImage: {
path: 'img/sampleImage2.png',
name: 'SampleImage',
},
theme: blackTheme,
initMenu: 'filter',
menuBarPosition: 'left'
},
cssMaxWidth: 700,
cssMaxHeight: 1000,
usageStatistics: false
});
window.onresize = function() {
imageEditor.ui.resizeEditor();
}
function dataURLtoBlob(dataurl) {
var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while(n--){
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], {type:mime});
}
jQuery(document).ready(function ($) {
$('.tui-image-editor-download-btn').on('click', function (e) {
var blob = dataURLtoBlob(imageEditor.toDataURL());
var formData = new FormData();
formData.append('croppedImage', blob, 'sampleimage.png');
$.ajax({
url: '/files/upload_files/', // upload url
method: "POST",
data: formData,
success: function (data) {
alert('UPLOADED SUCCESSFULLY, PLEASE TRY AGAIN...');
},
error: function(xhr, status, error) {
alert('UPLOAD FAILED, PLEASE TRY AGAIN...');
}
});
return false;
});
});
</script>
Added in some false statements so that the object form can be sent.
jQuery(document).ready(function ($) {
$('.tui-image-editor-download-btn').on('click', function (e) {
var blob = dataURLtoBlob(imageEditor.toDataURL());
var formData = new FormData();
formData.append('croppedImage', blob, 'sampleimage.png');
$.ajax({
contentType: false, //added
processData: false, //added
url: '/files/upload_files/', // upload url
method: "POST",
data: formData,
success: function (data) {
alert('UPLOADED SUCCESSFULLY, PLEASE TRY AGAIN...');
},
error: function(xhr, status, error) {
alert('UPLOAD FAILED, PLEASE TRY AGAIN...');
}
});
return false;
});
});
Related
This is the image of form which I have designed in my project Now my requirement is to upload multiple files and with other form values over a single backend call.
<script>
<form class="form-horizontal" name="addColorForm" id="addColorForm"
enctype="multipart/form-data"
method="POST">
//Colour Name and Code fileds
//Files Uploader Plugin (Dropzone)
<input type="file" name="artworkFiles[]" style="visibility: hidden"/>
</form>
Now my script part
<script>
var validCode = function () { // my custom validation };
FormValidation.validators.validCode = validCode;
FormValidation.formValidation(
document.getElementById('addColorForm'),
{
fields: {
colorName: {
validators: {
notEmpty: {
message: '${message(code:"blank.error.message", default:"This field must be entered")}'
},
}
},
},
plugins: { //Learn more: https://formvalidation.io/guide/plugins
trigger: new FormValidation.plugins.Trigger(),
// Bootstrap Framework Integration
bootstrap: new FormValidation.plugins.Bootstrap(),
// Validate fields when clicking the Submit button
submitButton: new FormValidation.plugins.SubmitButton(),
// Submit the form when all fields are valid
// defaultSubmit: new FormValidation.plugins.DefaultSubmit(),
}
}
).on('core.form.valid', function () {
saveColor();
});
function saveColor() {
var url = "url";
var form = $("#createArtworkForm");
var formData = new FormData(form[0]);
$.ajax({
url: url,
type: 'POST',
enctype: 'multipart/form-data',
data: formData,
success: function (data) {},
cache: false,
contentType: false,
processData: false,
error: function () { }
});
}
var artworkColorsFiles = $('#kt_dropzone').dropzone({
url: "https://www.google.com", // Set the url for your upload script location
paramName: "media", // The name that will be used to transfer the file
maxFiles: 1,
maxFilesize: 40, // MB
addRemoveLinks: true,
acceptedFiles: "image/*",
autoProcessQueue: false,
accept: function (file) {
//Logic to add multiple files in an input type hidden which is declared above
let fileReader = new FileReader();
fileReader.readAsDataURL(file);
fileReader.onloadend = function () {
let content = fileReader.result;
$('#artworkFiles').val(content);
file.previewElement.classList.add("dz-success");
}
file.previewElement.classList.add("dz-complete");
}
});
</script>
My questions is how to implement this or how should i add my all files(max 3) in a input type file field declared as visibility hidden.
The same I did in my project here is the code hope it will help you.
you have to use the dropzone function to send file and form data in sendingmultiple function you have to add a loop through your formdata enter code here
var data = $("form#OpportunityForm").serializeArray();
$.each(data, function (key, el) {
.append(el.name, el.value);
});
$(document).ready(function () {
zdrop = new Dropzone('#dropzone', {
url: '#Url.Action("SaveOpportunity", "Masters")',
maxFiles: 500,
maxFilesize: 300,
parallelUploads: 100,
addRemoveLinks: true,
autoProcessQueue: false,
uploadMultiple: true,
removeFilePromise: function () {
return new Promise((resolve, reject) => {
let rand = Math.floor(Math.random() * 3)
console.log(rand);
if (rand == 0) reject('didnt remove properly');
if (rand > 0) resolve();
});
},
sendingmultiple: function (file, xhr, formData) {
var data = $("form#OpportunityForm").serializeArray();
$.each(data, function (key, el) {
.append(el.name, el.value);
});
debugger
$("form#OpportunityForm").find("input[type=file]").each(function (index, field) {
const file = field.files[0];
formData.append('itemfile', file);
});
},
successmultiple: function (file, responseText) {
jQuery('form#OpportunityForm').find('textarea, input').each(function () {
jQuery(this).val('');
});
clear();
swal.fire("Opportunity Details Saved!", "Opportunity details Saved Successfully!", "success");
OpportunityMstList();
GetOpportunityMstList();
location.reload();
$("#myModal").modal('hide');
},
});
after adding this on the form submit button click you have to add this for creating blob file when you post data without image file.
jQuery(document).on('click', 'button#saveOpportunity', function (e) {
e.preventDefault();
if ($("#OpportunityForm").validate().form()) {
if (zdrop.files.length == 0) {
var blob = new Blob();
blob.upload = { 'chunked': zdrop.defaultOptions.chunking };
zdrop.uploadFile(blob); // just submit the form
} else if (zdrop.getRejectedFiles().length > 0) {
alert("The attached file is invalid");
} else {
zdrop.processQueue();
}
}
});
I am trying to call a vue method from javascript function but can't make it work. The method I am trying to call is app.onChangePlant(val) It turns out that the value is not called.
Is it because of the vue is not yet available when I declared the javascript function?
This is the error I am receiving
plant-consumer:222 Uncaught TypeError: app.onChangePlant is not a function
at onChangePlantSelect (plant-consumer:222)
at HTMLSelectElement.onchange (plant-consumer:399)
at Object.trigger (app.js:14973)
at HTMLSelectElement.<anonymous> (app.js:15045)
at Function.each (app.js:6863)
at jQuery.fn.init.ea
Code:
<script type="module" defer>
const setting = {
url: {
findUsage: "{{ route('admin.plant-consumer.find-usage') }}",
usageCsvDownload: "{{ route('admin.plant-consumer.usage-csv-download') }}",
},
date: {
date_default: moment("{{ $defaultDate }}", 'YYYY/MM/DD').toDate()
}
};
const app = new Vue({
el: '#app',
data: {
url: setting.url,
plantId: '',
isLoading: false,
rangeFilter: 'daily',
byMonth: false,
csvDownloadUrl: '',
date: setting.date.date_default,
month: setting.date.date_default,
// datepicker用設定
DatePickerFormat: 'yyyy/MM/dd',
MonthPickerFormat: 'yyyy/MM',
disabledDates: {
from: new Date()
},
ja_vdp: vdp_translation_ja.js
},
components: {
'vuejs-datepicker': vuejsDatepicker
},
watch: {
rangeFilter: function () {
this.byMonth = this.rangeFilter === 'monthly';
this.getData(1);
},
},
methods: {
onChangePlant: function(event) {
this.plantId = event.target.value;
this.getData(1);
},
onChangeDate: function () {
this.getData(1);
},
onChangeMonth: function () {
this.getData(1);
},
getData: function(page) {
let that = this;
let date = that.date;
that.isLoading = true;
that.csvDownloadUrl = '';
if (that.byMonth) {
date = that.month;
}
if(that.plantId && ((date)))
{
let data = {
plant : that.plantId,
date : that.formatDateForRequest(date),
byMonth: that.byMonth,
page : page,
};
let url = that.url.usageCsvDownload
+ '?plant=' + data.plant
+ '&date=' + data.date
+ '&byMonth=' + data.byMonth;
// console.log(url);
$.ajax(
{
url: that.url.findUsage,
type: "get",
datatype: "html",
data: data,
cache: false
}).done(function(data){
$("#consumer_table_generate").empty().html(data);
that.csvDownloadUrl = url;
}).fail(function(jqXHR, ajaxOptions, thrownError){
alert('No response from server');
}).always(function() {
that.isLoading = false;
});
}
else
{
$("#consumer_ratio_body").empty();
that.isLoading = false;
}
}
},
mounted: function () {
let vueObj = this;
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).on('click', '.pagination a', function(event)
{
event.preventDefault();
let $this = $(this);
$('#consumer_table_generate li').removeClass('active');
$this.parent('li').addClass('active');
var page = $this.attr('href').split('page=')[1];
vueObj.getData(page);
});
}
});
$(document).ready(function () {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
});
</script>
<script>
function onChangePlantSelect(val) {
console.log(val);
app.onChangePlant(val);
};
</script>
const App = {
data: {
url: setting.url,
plantId: '',
isLoading: false,
rangeFilter: 'daily',
byMonth: false,
csvDownloadUrl: '',
date: setting.date.date_default,
month: setting.date.date_default,
// datepicker用設定
DatePickerFormat: 'yyyy/MM/dd',
MonthPickerFormat: 'yyyy/MM',
disabledDates: {
from: new Date()
},
ja_vdp: vdp_translation_ja.js
},
components: {
'vuejs-datepicker': vuejsDatepicker
},
watch: {
rangeFilter: function () {
this.byMonth = this.rangeFilter === 'monthly';
this.getData(1);
},
},
methods: {
onChangePlant: function(event) {
this.plantId = event.target.value;
this.getData(1);
},
onChangeDate: function () {
this.getData(1);
},
onChangeMonth: function () {
this.getData(1);
},
getData: function(page) {
let that = this;
let date = that.date;
that.isLoading = true;
that.csvDownloadUrl = '';
if (that.byMonth) {
date = that.month;
}
if(that.plantId && ((date)))
{
let data = {
plant : that.plantId,
date : that.formatDateForRequest(date),
byMonth: that.byMonth,
page : page,
};
let url = that.url.usageCsvDownload
+ '?plant=' + data.plant
+ '&date=' + data.date
+ '&byMonth=' + data.byMonth;
// console.log(url);
$.ajax(
{
url: that.url.findUsage,
type: "get",
datatype: "html",
data: data,
cache: false
}).done(function(data){
$("#consumer_table_generate").empty().html(data);
that.csvDownloadUrl = url;
}).fail(function(jqXHR, ajaxOptions, thrownError){
alert('No response from server');
}).always(function() {
that.isLoading = false;
});
}
else
{
$("#consumer_ratio_body").empty();
that.isLoading = false;
}
}
},
mounted: function () {
let vueObj = this;
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).on('click', '.pagination a', function(event)
{
event.preventDefault();
let $this = $(this);
$('#consumer_table_generate li').removeClass('active');
$this.parent('li').addClass('active');
var page = $this.attr('href').split('page=')[1];
vueObj.getData(page);
});
}
}
const app = Vue.createApp(App)
const vm = app.mount('#blog-posts-demo')
vm.remove(123456)
//this way you guarantee the app is properly mounted, by the time you call
I don't know why would you like to do that but if it's neccessary you can try to use window eventlisteners:
https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events
In your component you can add an eventlistener that call your method, in js script tage you can fire an event, if your component ready it will call the method.
I never did this before it's just a theory :)
edit: I tried it, but your component is not mounted when you want to fire the event in script tag
enter code hereI have read several answers about this question, but no one works.
I have the following code but my HttpPostedFileBase[] array is always null.
The Other parameters has the right value, but the HttpPostedFileBase[] is always null.
What am i missing??
$('#myFile').on('change', function (e) {
var fileName = e.target.files[0].name;
archivosProcesar = new FormData();
for (var i = 0; i <= e.target.files.length -1; i++) {
archivosProcesar.append(i, e.target.files[i]);
}
});
function aplicarFragmentacion() {
var ids = obtenerAfiliadosSeleccionados();
var data = {
fragmento1: parseInt($('#fragmento1').val()),
fragmento2: parseInt($('#fragmento2').val()),
segmentos: ids,
archivos: archivosProcesar
}
if (!validarProcentajes() & !validarSeleccionados(ids)) {
$.ajax({
data: data,
url: urlAplicarFrag,
type: 'POST',
processData: false,
beforeSend: function () {
//$("#resultado").html("Procesando, espere por favor...");
},
success: function (data) {
onSuccessAplicarFragmentacion(data);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR.responseText);
onError(jqXHR.responseText);
}
});
}
}
Controller.cs
public async Task<ActionResult> AplicarFragmentacion(decimal fragmento1, decimal fragmento2, string[] segment\
os, HttpPostedFileBase[] archivos)
{
List<Credito> lstSegmentos = new List<Credito>();
try
{
ProgressHub.SendMessage("Iniciando proceso de fragmentación...", 10);
lstSegmentos = await FragmentacionNegocio.AplicarFragmentacion(fragmento1, fragmento2, segmentos)\
;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
return Json(lstSegmentos, JsonRequestBehavior.AllowGet);
}
Try submitting a FormData object, not an anonymous object with a FormData field. Also it is my understanding that the contentType should be set to false.
var formData = new FormData();
formData.append('fragmento1', parseInt($('#fragmento1').val());
formData.append('fragmento2', parseInt($('#fragmento2').val());
formData.append('segmentos', obtenerAfiliadosSeleccionados());
formData.append('archivos', $('#fileupload')[0].files[0]);
$.ajax({
type: 'POST',
data: formData,
url: urlAplicarFrag,
type: 'POST',
processData: false,
contentType: false,
[...]
});
The fix was to use this plug in
https://jquery-form.github.io/form/
In this way
$(this).ajaxSubmit({
url: urlAplicarFrag,
data: {
fragmento1: parseInt($('#fragmento1').val()),
fragmento2: parseInt($('#fragmento2').val()),
segmentos: ids,
fechaReenvio: $('#fecha-reenvio').val()
},
success: function (data) {
onSuccessAplicarFragmentacion(data);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR.responseText);
onError(jqXHR.responseText);
}
});
check the plugin website
getMediaBinary: function() {
var file = document.getElementById('photo').files[0],
reader = new FileReader(),
deferred = $.Deferred();
reader.onloadend = function () {
return deferred.resolve(reader.result);
};
reader.readAsBinaryString(file);
return deferred.promise();
},
getMediaData: function() {
var file = document.getElementById('photo').files[0],
reader = new FileReader(),
deferred = $.Deferred();
reader.onloadend = function () {
return deferred.resolve(reader.result);
};
reader.readAsDataURL(file);
return deferred.promise();
},
uploadMedia: function() {
var formData = new FormData();
$.when(JTWEET.getMediaBinary(), JTWEET.getMediaData() ).then(function(media, media_data) {
formData.append('media', media);
formData.append('media_data', media_data);
return $.ajax({
url: JTWEET.routerUrl + 'https://upload.twitter.com/1.1/media/upload.json',
type: 'POST',
// data: { media: document.getElementById('photo').files[0].name, media_data: JTWEET.getMediaData() },
data: formData,
contentType: false,
processData: false,
success: function() {
console.dir(arguments);
},
error: function() {
console.dir(arguments);
}
});
});
},
I'm getting the next error:
{"errors":[{"code":38,"message":"media parameter is missing."}]}
What am I missing ?
Try checking this one out - https://twittercommunity.com/t/post-media-upload-json-always-returns-media-parameter-is-missing/27962
Figured it out finally. Two things are important here:
1. the parameter name has to be “media”, not “media[]”
2. Do not set the contentType property. It prevents a Content-Type header with the correct boundary value from being automatically created.
A correct options object looks like this:
var options = {
"oAuthServiceName":"twitter",
"oAuthUseToken":"always",
method: "POST",
payload: { "media" : imageblob }
};
I'm developing a small function for an image-upload. This image-upload resizes selected pictures on the client and upload the resized image.
This works, but the browser will hang a lot between "resizes-functionality".
This is my code:
function manageImage(file) {
if (!file) return;
var mime = file.type;
var src = URL.createObjectURL(file);
loadImage.parseMetaData(file, function (data) {
var options = { maxWidth: 1920, maxHeight: 1920, canvas: true };
if (data.exif) {
options.orientation = data.exif.get('Orientation');
}
loadImage(file,
function (img, test) {
loaded++;
var formData = new FormData();
formData.append("image", dataURI);
$.ajax({
url: "/URL",
data: formData,
cache: false,
contentType: false,
processData: false,
async: false,
type: "POST",
success: function (resp) {
}
}).error(function () {
}).done(function () {
if (loaded < checkedFiles.length) {
manageImage(files[loaded]);
} else {
//FINISHED
}
});
},
options);
});
}
manageImage(files[0]);
This funcition is recursive, because i had some problems with the iteration (browser-hang, memory and cpu-usage).
Additionally, i'm using this library for EXIF-Data and correct orientation on mobile phones:
https://github.com/blueimp/JavaScript-Load-Image
With one or two selected pictures (e.g. 7MB) it works perfect, but i want to upload maybe 50 pictures.
It would be great if someone can give me a clue?!