Using amazon s3 storage with summernote #72

Closed
ankur1708 opened this Issue Oct 13, 2013 · 51 comments

Projects

None yet
@ankur1708

Summernote converts uploaded image as a base64 data which is too large to store.
Is there way to inject amazon s3 service, so that only link gets stored in db?

@hackerwins hackerwins was assigned Oct 13, 2013
@drewhamlett

This is what I have. Sorry for the coffeescript. It only does the first image dragged in right now.

sendFile = (file, callback) ->

  data = new FormData()
  data.append("file", file)
  $.ajax {
    url: '/upload',
    data: data,
    cache: false,
    contentType: false,
    processData: false,
    type: 'POST',
    success: (data) ->
      callback(data)
  }

$ () ->
  $post = $('#post-create')
  $post.summernote {
    height: "350px",
    onImageUpload: (files, editor, welEditable) ->
      sendFile files[0], (data) ->
        url = "#{data.scheme}://#{data.host}#{data.path}"
        editor.insertImage(welEditable, url)

Rails controller

class UploadsController < ApplicationController

  def create
    @file = params[:file].tempfile
    s3 = AWS::S3.new
    random = SecureRandom.hex
    image = s3.buckets['my-bucket'].objects.create("#{random}.jpg", @file)

    render(json: image.public_url)
  end
end
@ankur1708

Thanks drewhjava. That helps.
I will modify it to delete images from s3 as well on removing images from editor content and post it here soon.

@hackerwins
Member

@ankur1708, @drewhjava Great!!! 👍

@hackerwins hackerwins added a commit that referenced this issue Nov 3, 2013
@hackerwins hackerwins Update Docs for #72 23bf90a
@moffepoffe

based on @drewhjava code.

jQuery(document).ready(function() {
    jQuery('#summernote').summernote({
        height: "500px",
        onImageUpload: function(files, editor, welEditable) {
            sendFile(files[0],editor,welEditable);
        }
    });
});
function sendFile(file,editor,welEditable) {
    data = new FormData();
    data.append("file", file);
    $.ajax({
        data: data,
        type: "POST",
        url: "/ajax/saveimage",
        cache: false,
        contentType: false,
        processData: false,
        success: function(url) {
                editor.insertImage(welEditable, url);
        }
    });
}

PHP server side

$f3->route('POST /ajax/saveimage', function($f3){
        $name = randomString();
        $ext = explode('.',$_FILES['file']['name']);
        $filename = $name.'.'.$ext[1];
        $destination = '/home/xxx/public_html/images/'.$filename;
        $location =  $_FILES["file"]["tmp_name"];
        move_uploaded_file($location,$destination);
        echo 'http://xxx.com/images/'.$filename;
    });
function randomString() {
    return md5(rand(100, 200));
}

will work on it to be dynamic :-)

@eyeris
eyeris commented Nov 13, 2013

Hi I have tried this code several times and everything works out until the,

success: function(url) {
editor.insertImage(welEditable, url);

The php function prints the correct image path and I can even access the stored file in browser address bar. but its doesn't insert to the editor. any suggestions

@titosemi

@eyeris Your php code has to return back the url to the file in order to be able to render it.

@mirivlad

@moffepoffe, @ankur1708 How do remove the picture from the server if it is removed in the editor? Please show me an example, do not have a high skill in javascript :(

@drewhamlett

@mirivlad I just leave it on the server. Your talking less then a cent. You should always run your images through imagemagick before uploading.

If I were doing it, I would implement a scraper that runs every day and listed out all images(older ones) on s3 and see if they existed in the posts.

Put it this way.

You store 10,000 100kb images(some will be smaller). That's 0.953674 gb. That's $0.01 on Amazon S3. I think it actually counts as free usage tier also.

http://calculator.s3.amazonaws.com/calc5.html

@mirivlad

@drewhjava Yes, I think you're right. Old habits are still with me :)

@drewhamlett

@mirivlad Look at the bright side, if you start storing millions of images on Amazon S3 that means your product is successful enough to hopefully have some income. Haha.

@mirivlad

@drewhjava I'm not going to store images in AS3. The project is small and will be located at the customer's hosting about which I know nothing. If the customer will be required to AS3 to store pictures, I realize it feature for an additional cash :)

@moffepoffe

@mirivlad i will try to fix the code for you later today :)

@mirivlad

@moffepoffe I would be inordinately grateful to you :)

@soomtong
Contributor

thanks friends!

@soomtong soomtong closed this Nov 29, 2013
@uro
uro commented Jan 15, 2014

Hello can anyone help me out?
Since two days i'm trying to figure out how to fix something that should work, but it doesn't (for whatever silly reason).
Sorry for posting this here, just thought it's not big enought to create a new issue.
I belive that a clever person would has a quick look an be able to point the problem whitin the matter of second :) apparently i'm not the cleverest one.

I'ive applied @moffepoffe's method into my project and when i try upload the pic, javascript console comes back with "Uncaught TypeError: Cannot read property '0' of undefined ", second line of pasted text

      onImageUpload: function(files, editor, welEditable) {
            sendFile(files[0],editor,welEditable);
        }

My code:

  $(document).ready(function(){
    $('select').select2();
    $('.note-editable').css('overflow','auto');
    $('.summernote').summernote({
        height: 400,
        onImageUpload: function(files, editor, welEditable) {
            
            sendFile(files[0],editor,welEditable);
        }
      });
    function sendFile(file,editor,welEditable) {
      data = new FormData();
      data.append("file", file);
      console.log('image upload:', file, editor, welEditable);
      console.log(data);
      $.ajax({
          data: data,
          type: "POST",
          url: "upload/index/news",
          cache: false,
          contentType: 'multipart/form-data',
          processData: false,
          success: function(url) {
            editor.insertImage(welEditable, url);
          }
      });
    }
  });

PS: I have tested the upload function on the server side and it works.
PPS: When i uploading the pic to base64 it works fine too.

Now, using the mantioned method uploading pic to server does not work, (looks like the pic not be chosen correctly or for some reason it didn't follow the procedure of chooseing it)

Let me show debug:
a15005656

A big thank you to anyone who can put a hit of light on to this problem, any clues would highly appreciated 👍

@mjim
mjim commented Feb 6, 2014

@oparkadiusz Did you ever resolve this? I'm having the same problem. Summernote is my preferred editor but if my clients can't upload images, then it is useless.

@derek3x
derek3x commented Feb 11, 2014

In case anyone is looking through this issue for help.

I am using Summernote in a Python(Flask) web app. I used python with regex to find the base64 images that my form was submitting. I then converted them back to a proper image, saved it on the server and changed the img src link to be that of the image. It works great.

It could be used as a work around for some people if they have not thought of catching the base64 this way. I agree it seems a bit much considering it gets converted twice now, but I simply could not get the image upload to work with flask.

@pRdm
pRdm commented Feb 20, 2014

Amazon recently opened up support for CORS, which allows direct javascript interaction with its buckets.

In order to achieve this, first you have to update the CORS configuration of your S3 bucket.

This is what I use for allowing uploads via the POST action:

<CORSConfiguration>
    <CORSRule>
        <AllowedOrigin>https://www.yourdomain.com</AllowedOrigin>
        <AllowedMethod>POST</AllowedMethod>
        <AllowedHeader>*</AllowedHeader>
    </CORSRule>
    <CORSRule>
        <AllowedOrigin>*</AllowedOrigin>
        <AllowedMethod>GET</AllowedMethod>
    </CORSRule>
</CORSConfiguration>

Here's a helpful article from Amazon(http://aws.amazon.com/articles/1434) detailing what you need inside the POST request.

I pre-render the base64 encoded signature and policy strings in the controller:

def load_s3_metadata
  @signature = signature
  @policy = policy
end

def signature(options = {})
  Base64.encode64(
    OpenSSL::HMAC.digest(
      OpenSSL::Digest::Digest.new('sha1'),
      SECRET_ACCESS_KEY,
      policy({ secret_access_key: SECRET_ACCESS_KEY })
    )
  ).gsub(/\n/, '')
end

def policy(options = {})
  Base64.encode64(
    {
      expiration: 30.minutes.from_now.utc.strftime('%Y-%m-%dT%H:%M:%S.000Z'),
      conditions: [
        { bucket: MY_BUCKET },
        { acl: 'public-read' },
        { success_action_status: '201' },
        ["starts-with", "$key", "my_folder/"],
        ["content-length-range", 0, 2097152]
      ]
    }.to_json
  ).gsub(/\n|\r/, '')
end

The conditions inside policy can be modified to fit your requirements. They are outlined in the above Amazon article.

Now in the javascript code (this upload gets triggered in summernote's onImageUpload callback)

$(document).ready(function() {
  $('.summernote').summernote({
    height: 500,
    onImageUpload: function(files, editor, welEditable) {
      sendFile(files[0], editor, welEditable);
    }
  });

  function sendFile(file, editor, welEditable) {
    formData = new FormData();
    formData.append('key', 'my_folder/' + file.name);
    formData.append('AWSAccessKeyId', '<%= ACCESS_KEY %>');
    formData.append('acl', 'public-read');
    formData.append('policy', '<%= @policy %>');
    formData.append('signature', '<%= @signature %>');
    formData.append('success_action_status', '201');
    formData.append('file', file);

    $.ajax({
      data: formData,
      dataType: 'xml',
      type: "POST",
      cache: false,
      contentType: false,
      processData: false,
      url: "https://<%= MY_BUCKET %>.s3-ap-southeast-2.amazonaws.com/",
      success: function(data) {

        // getting the url of the file from amazon and insert it into the editor
        var url = $(data).find('Location').text();
        editor.insertImage(welEditable, url);
      }
    });
  }
});

And voila!

p.s. note that its important to have the following in the ajax or jQuery is going to try and encode the request, resulting in a malformed POST error from Amazon.

  contentType: false,
  processData: false,
@mjim
mjim commented Feb 24, 2014

@pRdm Thank you for the in-depth response! It now works for me using Php.

Here is what I use:
(Php from this page: http://www.plupload.com/docs/Upload-to-Amazon-S3#prepare-server-side )

<?php
$bucket = 'my_bucketname';
$folder = 'demo';

// these can be found on your Account page, under Security Credentials > Access Keys
$accessKeyId = 'replace with your access key id';
$secret = 'replace with your secret access key';

$policy = base64_encode(json_encode(array(
  // ISO 8601 - date('c'); generates uncompatible date, so better do it manually
  'expiration' => date('Y-m-d\TH:i:s.000\Z', strtotime('+2 days')), 
  'conditions' => array(
    array('bucket' => $bucket),
    array('acl' => 'public-read'),
    array('success_action_status' => '201'),
    array('starts-with', '$key', $folder.'/')
  )
)));

$signature = base64_encode(hash_hmac('sha1', $policy, $secret, true));

?>

And then my sendFile function with Php:

        function sendFile(file, editor, welEditable) {
          formData = new FormData();
          formData.append('key', '<?php echo $folder; ?>/' + file.name);
          formData.append('AWSAccessKeyId', '<?php echo $accessKeyId; ?>');
          formData.append('acl', 'public-read');
          formData.append('policy', '<?php echo $policy; ?>');
          formData.append('signature', '<?php echo $signature; ?>');
          formData.append('success_action_status', '201');
          formData.append('file', file);

          $.ajax({
            data: formData,
            dataType: 'xml',
            type: "POST",
            cache: false,
            contentType: false,
            processData: false,
            url: "https://<?php echo $bucket ?>.s3.amazonaws.com/",
            success: function(data) {
              // getting the url of the file from amazon and insert it into the editor
              var url = $(data).find('Location').text();
              editor.insertImage(welEditable, url);
            }
          });
        }
@jaequery
jaequery commented Mar 9, 2014

Hello all, someone please help. i don't know why image upload works in the github example page, but not in my local app. i'm just testing on the example page, is there some restriction I should be aware of?

@seanbotha123

anyone who has .NET code for this (preferably VB)? I love summernote, but need to use s3 and .net, I have no idea of how Ruby works so struggling with converting.

Thanks! :)

@hamerw
hamerw commented Jul 19, 2014

This is my 2-cents for a php solution...
setting up summernote...

jQuery(document).ready(function() {
    jQuery('#summernote').summernote({
        height: "500px",
        onImageUpload: function(files, editor, $editable) {
           sendFile(files[0],editor,$editable);
        }
    });
    function sendFile(file,editor,welEditable) {
    data = new FormData();
    data.append("file", file);
      $.ajax({
          url: "saveimage.php",
          data: data,
          cache: false,
          contentType: false,
          processData: false,
          type: 'POST',
          success: function(data){
          alert(data);
            editor.insertImage(welEditable, data);
          },
         error: function(jqXHR, textStatus, errorThrown) {
           console.log(textStatus+" "+errorThrown);
         }
      });
    }
});

php file... saveimage.php

<?php
// A list of permitted file extensions
$allowed = array('png', 'jpg', 'gif','zip');

if(isset($_FILES['file']) && $_FILES['file']['error'] == 0){

    $extension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);

    if(!in_array(strtolower($extension), $allowed)){
        echo '{"status":"error"}';
        exit;
    }

    if(move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/'.$_FILES['file']['name'])){
        $tmp='uploads/'.$_FILES['file']['name'];
        echo 'uploads/'.$_FILES['file']['name'];
        //echo '{"status":"success"}';
        exit;
    }
}

echo '{"status":"error"}';
exit;

and that's it. Unless you want to move the image to a different directory, but that's for you to figure out.. :)

@hamerw
hamerw commented Jul 19, 2014

Hey

I'm not sure how you have things setup.. but when I replace your url: img_upload.php with my url:saveimage.php it works fine. I have posted my saveimage.php in the blog.

Wayne.

On Saturday, July 19, 2014 12:43:53 PM, suyudo notifications@github.com wrote:

i get error like that.... how to solved it ?
my code
$(document).ready(function() { $('#summernote').summernote({ height: 300, minHeight: null, maxHeight: null, onImageUpload: function(files, editor, welEditable) { data = new FormData(); data.append("file", files[0]); $.ajax({ data: data, type: "POST", url: "img_upload.php", cache: false, contentType: false, processData: false, success: function(data) { alert(data); editor.insertImage(welEditable,data); }, error: function(jqXHR, textStatus, errorThrown) { console.log(textStatus+" "+errorThrown); } }); }, focus: true, toolbar: [ //[groupname, [button list]] ['style', ['bold', 'italic', 'underline', 'clear']], ['font', ['strikethrough']], ['fontsize', ['fontsize']], ['color', ['color']], ['para', ['ul', 'ol', 'paragraph']], ['height', ['height']], ['picture',['picture']] ] , onkeyup: function(e) { console.log(sHTML); }
}); });

Reply to this email directly or view it on GitHub.

@greerde
greerde commented Aug 31, 2014

Is there an API call to add a class to the generated HTML IMG tag? Specifically, I would like the ability to add the bootstrap img-responsive class to any image uploaded via Summernote.

I have thought about doing it when the the rich text is actually displayed on another page (not in the editor) - but that's not pretty.

Another option is to modify the code within the editor during onblur or similar.

@Xeoncross

I keep seeing sendFile(files[0],editor,$editable); in these comments. Shouldn't that be a foreach/each loop over files?

https://github.com/HackerWins/summernote/blob/develop/dist/summernote.js#L3737

onImageUpload: function(files, editor, $editable) {
        $.each(files, function (idx, file) {
            sendFile(file,editor,$editable,file.name);
        });
},
@sangyoo91

@pRdm Hello Patrick. I'm trying to follow some of these methods. I'm using Meteor. So I'm working with Javascript / Jquery, and your answer is the most closest I am getting. I am a completely new beginner and linking summer note to S3 has been a big difficult task for me. Could you kindly explain to me which parts I have to edit to my own settings from your example so I can study it and try to make it work? Thank you :)

@ste6an
ste6an commented Dec 16, 2014
onImageUpload: function(files, editor, welEditable) {
    sendImage(files).done(function(urls){
        $.each(urls, function(idx, url){
            editor.insertImage(welEditable, url);
        });
    });
}

sendImage = function(files) {
    var defer = $.Deferred();
    $.when.apply($, $.map(files, function(file){
        var data = new FormData();
        data.append("file", file);
        return $.ajax({
            data: data,
            type: "POST",
            url: "/uploadimage",
            contentType: false,
            processData: false
        })
    })).done(function(){
        console.log(arguments);
        if (files.length == 1){
            defer.resolve([arguments[0].url]);
        }else{
            defer.resolve($.map(arguments, function(responseData){
                return responseData[0].url;
            }));
        }
    });

    return defer.promise();
};
@WilsonFpz

If the dragged image by user is not from local desktop, but from the same html, such as a thumbnail.
How could make the summernote identifier the "src" and attached to the editor zone automatically?
Thanks.
[edited: Closed#841]

@EvilCult
EvilCult commented May 5, 2015

I've tried these codes, but no one worked. The php code is ok, but jQuery got an error at:

success: function(url) {
editor.insertImage(welEditable, url);

And, here is my solution...In case someone got the same problem..
based on @drewhamlett

    function setSummerNote () {
        $('#summernote').summernote({
            height: 300,  
            focus: true,
            onImageUpload: function(files) {
                sendFile(files[0]);
            }
        });
    }
    function sendFile(file) {
        data = new FormData();
        data.append("file", file);
        $.ajax({
            data: data,
            type: "POST",
            url: "xxxx.php",// your php url
            cache: false,
            contentType: false,
            processData: false,
            success: function(url) {
                $('#summernote').summernote('editor.insertImage', url);
            }
        });

Hope this could help someone~

@easylogic
Member

@EvilCult

can you tell me your summernote's version , browser' name and version ?

@EvilCult
EvilCult commented May 6, 2015

@easylogic
I download SummerNote from summernote.org, the version is 0.6.6 dist.
And I'm using Chrome version:41.0.2272.104 (64-bit).

Try the basic code like this:

var $summernote = $('#summernote');
$summernote.summernote({
  onImageUpload: function(files, editor, welEditable) {
    console.log(files, editor, welEditable);
  }
});

Then console shows this:

FileList {0: File, length: 1, item: function}0: Filelength: 1__proto__: FileList undefined undefined
@tangpanqing

@EvilCult
thanks,its helpful.

@seapy seapy referenced this issue in summernote/summernote-rails May 8, 2015
Closed

Image size restriction #22

@HaiNguyen13

@EvilCult just awesome 👍 thank you alot, i've stucked on this for days

@gzldx
gzldx commented May 11, 2015

@EvilCult I got the same problem..Thanks a lot
qq 20150512000333

@easylogic
Member

@gzldx

currently callback function was refactoring.

onImageUpload : function( files ) { 

   // get current editable container 
   var $note = $(this);  

   // use summernote api 
    $note.summernote('insertImage', 'http://wwww.google.com/logo.png');
}
@easylogic
Member

refer to #1044

@gzldx
gzldx commented May 13, 2015

@easylogic Thank you

@MACscr
MACscr commented Sep 25, 2015

So what is the final working solution?

@mozillazg

@MACscr Hi, I written a demo, maybe it'll help you: https://output.jsbin.com/taxire

@cssjockey

Here's how I implemented this:

jQuery Code

$('.wysiwyg').summernote({
    height: 500,
    onImageUpload: function(files, editor, welEditable) {
        // upload image to server and create imgNode...
        for (var i = files.length - 1; i >= 0; i--) {
            sendFile(files[i], this);
        }
    }
});

function sendFile(file, el) {
    var form_data = new FormData();
    form_data.append('file', file);
    $.ajax({
        data: form_data,
        type: "POST",
        url: "/media/ajaxupload",
        cache: false,
        contentType: false,
        processData: false,
        success: function(url) {
            $(el).summernote('editor.insertImage', url);
        }
    });
}

PHP Code should return the URL and this code will insert selected images to the editor.

Hope this helps.

@geekpeng
geekpeng commented Jan 7, 2016

maybe you can do like this(use base64 data at first, after upload successful use the response url replace img src, if take a lot time upload photos )

var postSummernot = $("#summernote-post").summernote({
    callbacks: {
        onImageUpload: function(files) {
            sendFile(files[0]);
        }
    }
});

function sendFile(file) {
    var formData = new FormData();
    formData.append("photo", file);

    var fileData = URL.createObjectURL(file);
    postSummernot.summernote('insertImage', fileData,function ($image) {
        $.ajax({
            url: "/photo/upload",
            data: formData,
            cache: false,
            contentType: false,
            processData: false,
            dataType:"json",
            type: 'POST',
            success: function(data){
                $image.attr('src', data.url);
            }
        });

    });
}
@achese15

Please can someone help me structure a code for summer note which will upload images to my server e.g "Bob.com/img/uploads" and then return the link back to the text editor so I could use it .....am new with this...please help...thank you

@piaoyizhimei

Hi,I use the onImageUpload ,I have the result, Before My Submit , An image's src is '/upload/1460626854.jpg', but after my submit, the src is 'blob:http%3A//a.test.com/c8f2bbe5-38b1-402c-949e-c00be1680c41'。How can i use the '/upload/1460626854.jpg' ? help !!!!

@jcshep
jcshep commented May 23, 2016

@piaoyizhimei
Did you ever figure this out? I'm having the same issue using 0.8.1

@mrrtee
Contributor
mrrtee commented Jul 31, 2016

I also got same problem as occurred with @piaoyizhimei , I'm using summernote v0.8.1, I can upload image to folder, but script return image as base64 code

@merajiyan

hello everyone,
i've tested some ways of this page but it didnt work correctly i just want upload my files into my folder instead of base64
any working way?

@lilicbush
lilicbush commented Oct 19, 2016 edited
$(document).ready(function () {
    var $summernote = $('.summernote-textarea').summernote({
        lang: 'ru-RU',
        height: 400,
        callbacks: {
            onImageUpload: function (files) {
                sendFile($summernote, files[0]);
            }
        }
    });
});

function sendFile($summernote, file) {
    var formData = new FormData();
    formData.append("file", file);
    $.ajax({
        url: '/new/files/upload',
        data: formData,
        cache: false,
        contentType: false,
        processData: false,
        type: 'POST',
        success: function (data) {
            $summernote.summernote('insertImage', data, function ($image) {
                $image.attr('src', data);
            });
        }
    });

}

@merajiyan

@lilicbush
when i put this code on my page and then i select a image to upload it doesnt appear on page!why?

@AlejandroSC
AlejandroSC commented Dec 23, 2016 edited

this is my code for js:

	$(document).ready(function() {
		$('#summernote').summernote({
			placeholder: 'Escribe aquí',
			lang: 'es-ES',
			height: 500,	// set editor height
			minHeight: null,	// set minimum height of editor
			maxHeight: null,	// set maximum height of editor
			focus: true,	// set focus to editable area after initializing summernote
			callbacks: {
				onImageUpload: function(files)
				{
					for(var i = 0; i < files.length; i++)
					{
						SubirImagen(files[i]);
					}
				}
			}
		});
	});

Function for upload image

	function SubirImagen(file)
	{
		if(file.type.includes('image'))
		{
			var name = file.name.split(".");
			name = name[0];  
			var data = new FormData();
			data.append('file', file);
			$.ajax({
				url: 'subir.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("El tipo de archivo que intentaste subir no es una imagen");
		}
	}

And for 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 = 'C:\\xampp\\htdocs\\summernote\\images\\' . $filename;
				$location = $_FILES["file"]["tmp_name"];
				move_uploaded_file($location, $destination);
				$message['url'] = '/summernote/images/' . $filename; 
				$message['is_ok'] = true;
			}
			else
			{
				$message['error'] = 'El tipo de archivo no es una imagen';
			}
		}
		else
		{
			$message['error'] = "La imagen no se ha subido correctamente error(".$_FILES['file']['error'].")";
		}	
	}
	else
	{
		$message['error'] = "No se ha enviado ningun archivo";
	}

	echo json_encode($message);
@Gorbulev-Sergey
Gorbulev-Sergey commented Dec 26, 2016 edited

Спасибо авторам за Summernote, отличный редактор.
Спасибо ребятам за примеры. На основании ваших примеров написал свой код для asn.net mvc:

VIEW:

<textarea name="содержимое" id="содержимое"></textarea>

`<script>

$(document).ready(function () {
    $('#содержимое').summernote({
       callbacks: {
           onImageUpload: function (files) {
                for (var i = 0; i < files.length; i++) {
                    send(files[i]);
                }
            }
        }
    });
});
function send(file) {
    if (file.type.includes('image')) {
        var name = file.name.split(".");
        name = name[0];
        var data = new FormData();
        data.append('file', file);
        $.ajax({
            url: '/Записи/Сохранить',
            type: 'POST',
            contentType: false,
            cache: false,
            processData: false,
            dataType: 'JSON',
            data: data,
            success: function (url) {
                $('#содержимое').summernote('insertImage', url);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                alert(textStatus + " " + errorThrown);
            }
        });
    }
}

</script>`

CONTROLLER:

[HttpPost]
public ActionResult Сохранить(System.Web.HttpPostedFileWrapper file)
{
if (!System.IO.File.Exists(Server.MapPath(file.FileName)))
{
file.SaveAs( Server.MapPath(file.FileName));
}
return Json(file.FileName);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment