How to set a limit on the number of uploaded images? - javascript

I used ckeditor 5 library for my textarea
I have this JS code
jQuery(function ($) {
ClassicEditor.create(document.querySelector('#history-description'), {
"toolbar": ["imageUpload", "bold", "link", "bulletedList", "uploadImage", "blockQuote"],
"ckfinder": {
"uploadUrl": "uploadImage.php",
"options": {
resourceType: ['jpeg', 'png', 'jpg']
}
},
}).then(editor => {
// editor.plugins.get('FileRepository').on('change:uploadTotal', evt => {
// console.log('Image uploaded evt');
// console.log(evt);
// });
}).catch(error => {
console.error(error);
});
});
How to set a limit on the number of uploaded images?
For example: the maximum number of uploaded files can only be 10

Related

How to open a file chooser inside a function

I am using quill editor and using a image handler for uploading images and it used to work fine but now i am moving to server side rendering and find this error of "File chooser dialog can only be shown with a user activation." while trying to open the file chooser for uploading the file.
imageHandler() {
//
let self=this
let image;
let image_extension;
var input = document.createElement("input");
// Set its type to file
input.type = "file";
// Set accept to the file types you want the user to select.
// Include both the file extension and the mime type
input.accept = "accept";
// set onchange event to call callback when user has selected file
input.addEventListener("change", onchange)
// dispatch a click event to open the file dialog
input.dispatchEvent(new MouseEvent("click")); //getting the error in this line.
input.onchange = async () => {
//
const file = input.files[0];
var ValidImageTypes = ["image/gif", "image/jpeg", "image/png", "image/jpg", "image/GIF", "image/JPEG", "image/PNG", "image/JPG"];
let file_type = file.type
let filename = file.name
let extension = filename.split('.').pop();
// debugger
if(ValidImageTypes.indexOf(file_type) >= 0){
if(file.size<=500000&&file.size>=50000){
// debugger
var fileToLoad = file
// loadImage(fileToLoad, (canvas) => {
// if(canvas){
// this.setState({
// image=canvas.toDataURL()
// image_extension=extension
// });
this.getBase64(file)
.then(result => {
// debugger
file["base64"] = result;
console.log("File Is",file.base64 );
const res = new Promise(function(resolve, reject) {
axios({
method:'post',
url:API_URL+'api/v1/postblogimage',
headers:{
'x-access-handler':loggedinUser.token
},
data:{
image: file.base64,
image_extension:image_extension,
userid:loggedinUser.userid
}
})
//axios.post(API_URL + 'api/v1/postblogimage', formData, config)
.then((response) => {
if (response.data.error == 'false' || response.data.error == false) {
if (response.data.status == 200 && response.data.message == "Image uploaded successfully") {
//
const range = self.quill.getSelection(true);
// Insert temporary loading placeholder image
// this.quill.insertEmbed(range.index, 'image', `${window.location.origin}/images/loaders/placeholder.gif`);
// Move cursor to right side of image (easier to continue typing)
self.quill.setSelection(range.index + 1);
// Remove placeholder image
self.quill.deleteText(range.index, 1);
// Insert uploaded image
let url=response.data.data[0].imageURL;
self.quill.insertEmbed(range.index, 'image', url);
self.quill.pasteHTML(range.index, <img src={url} class="blog-image-content" alt="Responsive image"/>);
}
}
// else if(response.data.error == 'true' || response.data.status == '500')
// componentProps.error('Sorry, Inappropriate image')
// }
}).catch((error) => {
// reject(Error("It broke"));
});
});
// }
// }, {orientation: true});
// }
})
}
else{
// componentProps.error(" Sorry, File size should be of size between 50 kb to 500kb")
}
}
else{
// this.setState({
// image_warning:'Invalid image type',
// image:'',
// image_extension:''
//})
// this.fileInput.value=''
}
};
}
//render function
<ReactQuill
ref={(el) => this.quillRef = el
}
onChange={this.handleChange}
placeholder={"You can insert images between your blog as well. Max image size to not exceed 500kb.Once you have uploaded an image, just wait, image will show up, if it is approved. Use #hashtags to highlight keywords/impact-terms in your blog, your blog might show up in trending keywords. Example: #gain"}
modules={{
toolbar: {
container: [
[{ header: '1' }, { header: [2,3, 4, 5, 6] }, { font: [] }],
[{ size: [ 'small', false, 'large', 'huge' ] }],
['bold', 'italic', 'underline', 'strike', 'blockquote'],
[{ list: 'ordered' }, { list: 'bullet' }],
['link', 'image', 'video'],
['clean'],
['code-block'],
[{ 'color': [] }, { 'background': [] }], // dropdown with defaults from theme
[{ 'align': [] }],
],
handlers: {
image: this.imageHandler
}
}
}}
/>
Before you click you must add the input to the document body
document.body.appendChild(input);

TUI image editor dynamic images

I'm stuck on an issue with the TUI Image Editor where the buttons don't work after using the loadImageFromURL function.
Currently, I load images from a gallery beneath the TUI editor with the exception of the first image using the scripts below:
My initialization
window.onresize = function() {
instance.ui.resizeEditor();
}
var instance = new tui.ImageEditor('#tui-image-editor', {
includeUI: {
theme: blackTheme, // or whiteTheme
menu: ['rotate'],
menuBarPosition: 'bottom'
},
loadImage: {
path: 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7',
name: 'Blank'
},
cssMaxWidth: 700,
cssMaxHeight: 500,
selectionStyle: {
cornerSize: 20,
rotatingPointOffset: 70
}
});
// Patch the loadImageFromURL of our tui instance instance:
instance.loadImageFromURL = (function() {
var cached_function = instance.loadImageFromURL;
function waitUntilImageEditorIsUnlocked(instance) {
return new Promise((resolve,reject)=>{
const interval = setInterval(()=>{
if (!instance._invoker._isLocked) {
clearInterval(interval);
resolve();
}
}, 100);
})
}
return function() {
return waitUntilImageEditorIsUnlocked(instance).then(()=>cached_function.apply(this, arguments));
};
})();
// Load an image and tell our tui imageEditor instance the new and the old image size:
instance.loadImageFromURL("{{ url('/') }}{{Storage::url('manifests/'.$images->first()->name)}}", "SampleImage").then(result=>{
instance.ui.resizeEditor({
imageSize: {oldWidth: result.oldWidth, oldHeight: result.oldHeight, newWidth: result.newWidth, newHeight: result.newHeight},
});
}).catch(err=>{
console.error("Something went wrong:", err);
})
/* instance.loadImageFromURL("{{ url('/') }}{{Storage::url('manifests/'.$images->first()->name)}}",'{{$images->first()->name}}').then(result => {
console.log('old : ' + result.oldWidth + ', ' + result.oldHeight);
console.log('new : ' + result.newWidth + ', ' + result.newHeight);
});*/
My script to select other images:
$(document).on('click', '.selectImage', function() {
var path = $(this).data('path');
$('#image_id').val($(this).data('image_id'));
instance.clearObjects().then(() => {
console.log('cleared');
instance.loadImageFromURL("{{ url('/') }}"+path,'name').then(result=>{
instance.ui.resizeEditor({
imageSize: {oldWidth: result.oldWidth, oldHeight: result.oldHeight, newWidth: result.newWidth, newHeight: result.newHeight},
});
console.log(result);
}).catch(err=>{
console.error("Something went wrong:", err);
})
});
});
Now, oddly enough, the images load fine. But the buttons don't do anything. If I highlight over the rotate button, it'll show a help popup of "Rotate" but won't actually do anything.
Do I have to reset the canvas somehow when loading the images?
I had a similar issue, you need to re-enable the menu by calling ui.activeMenuEvent(). So applying the changes to your code it would look like this
$(document).on('click', '.selectImage', function() {
var path = $(this).data('path');
$('#image_id').val($(this).data('image_id'));
instance.clearObjects().then(() => {
console.log('cleared');
instance.loadImageFromURL("{{ url('/') }}"+path,'name').then(result=>{
instance.ui.resizeEditor({
imageSize: {oldWidth: result.oldWidth, oldHeight: result.oldHeight, newWidth: result.newWidth, newHeight: result.newHeight},
});
instance.ui.activeMenuEvent();
console.log(result);
}).catch(err=>{
console.error("Something went wrong:", err);
})
});
});

Reset FilePond Input in Javascript

I have implemented Filepond uploaded in my page. When the user selects a file, I set that file on a html canvas for edits. However when the user wants to upload another file, filepond input retains last uploaded file.
I have tried FilePond.destroy(inputElement); after the file is successfully set on the canvas in the FilePond:addfile event.
$('.upload-file').filepond();
$.fn.filepond.registerPlugin(
FilePondPluginFileValidateType,
FilePondPluginFileValidateSize,
FilePondPluginImageResize,
FilePondPluginImageExifOrientation,
FilePondPluginImagePreview,
FilePondPluginImageTransform,
FilePondPluginImageCrop,
FilePondPluginImageValidateSize,
);
FilePond.setOptions({
labelIdle: 'Drag & Drop your file or <span class="filepond--label-
action"> Browse </span>',
maxFiles: 1,
allowDrop: true,
allowMultiple: false,
dropOnPage: true, //for page to work, element has to be false https://github.com/pqina/filepond/issues/113
dropOnElement: false,
labelTapToCancel: '', //we dont want to allow cancel
labelTapToUndo: '',
maxFileSize: intFileSizeInMB,
allowReplace: true,
allowRevert: false,
instantUpload: false
});
const pond = document.querySelector('.filepond--root');
pond.addEventListener('FilePond:addfile', e => {
console.log('File added', e.detail);
if (e.detail) {
if (e.detail.file && e.detail.file.file.name) {
SetFileOnCanvas(e.detail.file.file, e.detail.file.file.name);
const inputElement = document.querySelector('input[type="file"]');
FilePond.destroy(inputElement);
}
}
});
pond.addEventListener('FilePond:processfile', e => {
console.log('Process File COMPLETE', e.detail);
});
After a file is uploaded and set to Canvas the file upload input should be cleared and ready for another upload.
Working solution
var pond_ids = [];
if (pond.getFiles().length != 0) { // "pond" is an object, created by FilePond.create
pond.getFiles().forEach(function(file) {
pond_ids.push(file.id);
});
}
pond.removeFiles(pond_ids);
After upload file "Complete function"
you can do like this (simple example):
if (filePond.getFiles().length != 0) {
for (var i = 0; i <= filePond.getFiles().length - 1; i++) {
filePond.removeFile(filePond.getFiles()[0].id)
}
}
I know its too late but you can use
let filePond = FilePond.find(document.getElementById(filePondElementId));
if (filePond != null) {
//this will remove all files
filePond.removeFiles();
}
<script src="https://unpkg.com/filepond/dist/filepond.min.js"></script>
Assuming that you create your filepond instance through function create_pondProfile and your input has class filepond, in you filepond config in server block do like this:
server: {
url: '',
process: {
url: '/path/to/upload/',
headers: {'X-CSRF-TOKEN': csrf},
ondata: (formData) => {
return formData;
},
onload: (response) => {
FilePond.destroy(document.querySelector('.filepond'));
create_pondProfile('.filepond');
}
},
...
...
}
It will destroy current instance of filepond and creates new one after upload.

Picking images from PhotoLibrary not working - Ionic 4

I am implementing a picture upload functionality to my app which I am developing with Ionic 4. I'm using the native plugin camera and a few others to do the following:
async selectImage() {
const actionSheet = await this.actionsheet.create({
header: "Select Image source",
buttons: [{
text: 'Load from Library',
handler: () => {
this.takePicture(this.camera.PictureSourceType.PHOTOLIBRARY);
}
},
{
text: 'Use Camera',
handler: () => {
this.takePicture(this.camera.PictureSourceType.CAMERA);
}
},
{
text: 'Cancel',
role: 'cancel'
}
]
});
await actionSheet.present();
}
takePicture(sourceType: PictureSourceType) {
var options: CameraOptions = {
quality: 100,
sourceType: sourceType,
saveToPhotoAlbum: false,
correctOrientation: true
};
this.camera.getPicture(options).then(imagePath => {
var currentName = imagePath.substr(imagePath.lastIndexOf('/') + 1);
var correctPath = imagePath.substr(0, imagePath.lastIndexOf('/') + 1);
this.copyFileToLocalDir(correctPath, currentName, this.createFileName());
});
}
copyFileToLocalDir(namePath, currentName, newFileName) {
this.file.copyFile(namePath, currentName, this.file.dataDirectory, newFileName).then(success => {
this.presentToast('Dispongo a actualizar.');
this.updateStoredImages(newFileName);
}, error => {
// this.presentToast('Error while storing file.');
});
}
updateStoredImages(name) {
this.storage.get(STORAGE_KEY).then(images => {
let arr = JSON.parse(images);
if (!arr) {
let newImages = [name];
this.storage.set(STORAGE_KEY, JSON.stringify(newImages));
} else {
arr.push(name);
this.storage.set(STORAGE_KEY, JSON.stringify(arr));
}
let filePath = this.file.dataDirectory + name;
let resPath = this.pathForImage(filePath);
let newEntry = {
name: name,
path: resPath,
filePath: filePath
};
this.images = [newEntry, ...this.images];
this.ref.detectChanges(); // trigger change detection cycle
});
}
So, in the action sheet, when I press the first option (Load from Library) it opens the library and I can choose the picture without any problem. When I press ok, it throws an error: the error expected from the copyFileToLocalDir. However, if I do the same with the second option (Use Camera) and I take a photo with the camera, it loads it fine and I can store it later.
I can't find the problem, please help.
im using this code using ionic 3 and it's working fine .
and after i chose one image it will be uploading to firebase and on the same time view it at page.html
app.module.ts
you have to import
import { Camera } from "#ionic-native/camera";
import { File } from "#ionic-native/file";
and added them #providers
then use this code at page.ts which you will chose one image :
html view
<button ion-button full (click)="openGallery()">open gallery</button>
<img [src]="camel_profile_image_path" />
ts page
import { Camera, CameraOptions } from "#ionic-native/camera";
private camera: Camera,
async openGallery() {
try {
const opstions: CameraOptions = {
quality: 100,
targetHeight: 600,
targetWidth: 600,
destinationType: this.camera.DestinationType.DATA_URL,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE,
sourceType: this.camera.PictureSourceType.PHOTOLIBRARY,
correctOrientation: true
}
const result = await this.camera.getPicture(opstions);
const image = 'data:image/jpeg;base64,' + result;
const pictures = storage().ref('Profile Images/' + this.randomNumber + '.jpg');
pictures.putString(image, 'data_url');
this.base64Image = image;
this.camel_profile_image_path = this.randomNumber; // view the image on html page
this.slidetothis();
} catch (error) {
console.error(error);
}
}

Cancel uploads in onStatusChange

In our system we only allow uploads up to a specific number which can be done in multiple upload sessions. When the number of images in an upload session exceed this maximum number we are currently cancelling uploads in onStatusChange() instead of adjusting itemLimit:
thumbnailuploader = new qq.FineUploader({
element: document.getElementById('thumbnail-fine-uploader'),
template: "qq-simple-thumbnails-template",
request: {
endpoint: 'uploader/uploader.php'
},
thumbnails: {
placeholders: {
waitingPath: "uploader/waiting-generic.png",
notAvailablePath: "uploader/not_available-generic.png"
}
},
validation: {
allowedExtensions: ['jpeg', 'jpg', 'gif', 'png', 'bmp'],
itemLimit: 6
},
callbacks: {
onSubmit: function(id, fileName){
// console.log("submitting..." + id);
},
onStatusChange: function (id, oldStatus, newStatus) {
// This will check to see if a file that has been cancelled
// would equate to all uploads being 'completed'.
if(parseInt(galleryImages) + id + 1 > MaxUploads && newStatus !== qq.status.CANCELLED){
this.cancel(id);
return;
}
if (newStatus === qq.status.CANCELLED) {
check_done();
return;
}
},
onComplete: check_done,
onUpload: StartUpload
}
});
This seems to work well, but when switching on the debugger I get:
Error: [Fine Uploader 5.0.3] 1 is not a valid file ID to upload!
in
now: function(id) {
var name = options.getName(id);
if (!controller.isValid(id)) {
throw new qq.Error(id + " is not a valid file ID to upload!");
}
and a bunch of:
"[Fine Uploader 5.0.3] Caught exception in 'onStatusChange' callback - element is undefined"
Can this be fixed or are these messages harmless?
Thanks!

Categories

Resources