Javascript – Summernote image upload
I have a problem with editor Summernote. I want to upload images into a catalog on the server.
I have some script:
I tested this code and Works
Javascript
$(function () { // Summernote var IMAGE_PATH = 'https://alaminsobuj.net/themeorigin-news/'; $('#editor1').summernote({ callbacks: { onImageUpload: function(image) { uploadImage(image[0]); }, onMediaDelete : function(target) { deleteImage(target[0].src); } } }) function uploadImage(image) { var data = new FormData(); data.append("image", image); //var CSRF_TOKEN = $("#CSRF_TOKEN").val(); //site_url $.ajax({ url: "", cache: false, contentType: false, processData: false, data: data, type: "POST", success: function(url) { var image = IMAGE_PATH + url; $('#editor1').summernote("insertImage", image ) }, error: function(data) { console.log(data); } }); } function deleteImage(src) { $.ajax({ data: {src : src}, type: "POST", url: "", cache: false, success: function(response) { console.log(response); } }); } })#codeigniter codefunction upload_image(){ if (@$_FILES['image']['name']) { $config['upload_path'] = './assets/uploads/news/'; $config['allowed_types'] = 'gif|jpg|jpeg|png'; $config['overwrite'] = false; $config['max_size'] = 1024; $config['remove_spaces'] = true; $config['max_filename'] = 10; $config['file_ext_tolower'] = true; $this->load->library('upload', $config); if ( ! $this->upload->do_upload('image')) { $this->upload->display_errors(); return FALSE; } else { $data = $this->upload->data(); $image = $config['upload_path'].$data['file_name']; #------------resize image------------# $this->load->library('image_lib'); $config['image_library'] = 'gd2'; $config['source_image'] = $config['upload_path'].$data['file_name']; $config['create_thumb'] = FALSE; $config['maintain_ratio'] = FALSE; // $config['width'] = *; // $config['height'] = *; $this->image_lib->clear(); $this->image_lib->initialize($config); $this->image_lib->resize(); echo $image; #-------------resize image----------# } } } function delete_image(){ $src = $this->input->post('src'); $file_name = str_replace(base_url('/assets/uploads/news/'), '', $src); $img_path = FCPATH .'/assets/uploads/news/'. $file_name; unlink($img_path); if(unlink($img_path)){ echo 'File Delete Successfully'; } }#PHP CODE
if ($_FILES['image']['name']) {
if (!$_FILES['image']['error']) {
$name = md5(rand(100, 200));
$ext = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
$filename = $name.'.'.$ext;
$destination = '/assets/images/'.$filename; //change this directory
$location = $_FILES["file"]["tmp_name"];
move_uploaded_file($location, $destination);
echo 'http://test.yourdomain.al/images/'.$filename; //change this URL
} else {
echo $message = 'Ooops! Your upload triggered the following error: '.$_FILES['file']['error'];
}
}
Comments
Did this work for you, or did you hit something different? Leave a note.