Thay thế chức năng xử lý ảnh của Summernote
Lời mở đầu
Chào các bạn, hôm nay mục đích của mình khi đăng bài này là để lưu lại cách xử lý phần đăng ảnh của summernote thôi :v tại trên mạng có rất ít bài hướng dẫn và khi làm theo thì auto là tạch.Code JS cấu hình cho summernote
123456789101112131415161718$(document).ready(function() { $('#summernote').summernote({ placeholder: 'Mô tả chi tiết', height: 500, minHeight: null, maxHeight: null, focus: true, callbacks: { onImageUpload: function(files) { for(var i = 0; i < files.length; i++) { upFile(files[i]); } } } }); });
Code JS Function Upfile ảnh
123456789101112131415161718192021222324252627282930313233function upFile(file) { if(file.type.includes('image')) { var name = file.name.split("."); name = name[0]; var data = new FormData(); data.append('file', file); $.ajax({ url: 'upload_images.php', type: 'POST', contentType: false, cache: false, processData: false, dataType: 'JSON', data: data, success: function (response) { if(response.is_ok) { $('#summernote').summernote('insertImage', response.url, name); } else { console.log(response.error); } } }) .fail(function(e) { console.log(e); }); } else { console.log("Đừng cố tải cái gì lên khác ngoài ảnh :>"); } }
Code file upload_images.php
1234567891011121314151617181920212223242526272829303132<?php $message['is_ok'] = false; if(isset($_FILES)) { if(!$_FILES['file']['error']) { if(preg_match("/image/", $_FILES['file']['type'])) { $name = md5(rand(100, 200)); $ext = explode('.', $_FILES['file']['name']); $filename = $name . '.' . $ext[1]; $destination = '../views/assets/img/post/' . $filename; $location = $_FILES["file"]["tmp_name"]; move_uploaded_file($location, $destination); $message['url'] = '../views/assets/img/post/' . $filename; $message['is_ok'] = true; } else { $message['error'] = 'Bạn chỉ được up file ảnh thui nha :<'; } } else { $message['error'] = "Hình ảnh không được tải lên chính xác, lỗi (".$_FILES['file']['error'].")"; } } else { $message['error'] = "Không có tập tin nào được gửi đi"; } echo json_encode($message); ?>Chúc các bạn có một ngày vui vẻ nhớ :v
Sẽ thành công thuiiii
Thay thế chức năng xử lý ảnh của Summernote
Reviewed by Nguyen Nam Hong
on
12:30 AM
Rating:

Bình luận