Summernote Simple Method to Realize Image Upload Function
- 2021-07-02 23:05:27
- OfStack
Or go on to write an BootStrap web page recently as mentioned before... and then use the rich text editor, search it casually and choose this product
Then I found a very embarrassing problem... the picture uploading function is invalid... and then all kinds of searches are fruitless... Finally, I turned over the official document of Summernote and finally solved it. In short, I wrote down the solution process
The back-end part does not provide code, which is all over the street. It is assumed that the back-end gets the address of the uploaded file and returns it
First of all, attach a reference: Summernote official development document
Briefly talk about the implementation scheme of Summernote picture uploading function
First according to the official document provided by API, hook up the file upload event, and then use JS to upload the file again, and finally use API to insert the picture into the edit box
Originally, it was quite a simple question, but unfortunately, the official didn't know why he actually changed the interface writing... and then all the information searched on the Internet was pitted... although there were also reasons why I didn't search deeply enough
In a word, organize the two core SummernoteAPI, take over the file upload event and insert the picture, according to the official document description format as follows
// Take over the picture upload event
$('#summernote').summernote({
callbacks: {
onImageUpload: function(files) {
// Upload pictures to the server and insert pictures into the edit box
}
}
});
// Insert a picture
$('#summernote').summernote('insertImage', url, filename);
// See the official website provided above for a more detailed explanation API Document
Then you can easily implement the Summernote edit box that supports uploading pictures
The code is as follows:
$('#summernote').summernote({
callbacks: {
onImageUpload: function(files) {
// Upload pictures to the server, using formData Object, as for compatibility ... It is said that the lower version IE Not very friendly
var formData = new FormData();
formData.append('file',files[0]);
$.ajax({
url : 'upload',// Background file upload interface
type : 'POST',
data : formData,
processData : false,
contentType : false,
success : function(data) {
$('#summernote').summernote('insertImage',data,'img');
}
});
}
}
});
Finally, this only realizes the simplest picture upload function, which is not compatible and does not consider error and exception prompts at all.... Please modify it according to your needs