Murphy Tsai
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
      • Invitee
    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Versions and GitHub Sync Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
Invitee
Publish Note

Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

Your note will be visible on your profile and discoverable by anyone.
Your note is now live.
This note is visible on your profile and discoverable online.
Everyone on the web can find and read all notes of this public team.
See published notes
Unpublish note
Please check the box to agree to the Community Guidelines.
View profile
Engagement control
Commenting
Permission
Disabled Forbidden Owners Signed-in users Everyone
Enable
Permission
  • Forbidden
  • Owners
  • Signed-in users
  • Everyone
Suggest edit
Permission
Disabled Forbidden Owners Signed-in users Everyone
Enable
Permission
  • Forbidden
  • Owners
  • Signed-in users
Emoji Reply
Enable
Import from Dropbox Google Drive Gist Clipboard
   owned this note    owned this note      
Published Linked with GitHub
Subscribed
  • Any changes
    Be notified of any changes
  • Mention me
    Be notified of mention me
  • Unsubscribe
Subscribe
# [javasrcipt] Summernote 所見即所得編輯器達成圖片上傳 當使用者在後台管理商品資料的時候,必須用到編輯器讓使用者輸入資料,當然也少不了常常跟編輯期搭配使用的圖片上傳,這邊選用Shrine跟Summernote來當作例子,講解前端如何發起上傳圖片的request將圖片上傳到後端。 解釋一下:**Shrine** 是Rails 裡面一套圖片上傳的套件,而**Summernote** 是一套歷久彌新而且非常好用的所見即所得編輯器,你應該會常常在各大開源專案看到他的影子。 今天重點會著重在前端圖片上傳到後端,並回傳圖片位址的流程,在後端功能的實作上不會有有太詳細的解說。 Summernote 文件:https://summernote.org/ Shrine 文件:https://github.com/shrinerb/shrine ### OUTLINE 1. HTML編輯器功能說明 2. 圖片上傳流程解析 3. 實際程式碼 ### HTML編輯器功能說明: HTML編輯器的介面其實長得很像Word,有各種按鈕讓你設定跟編輯文字的外觀。只不過你在Web使用編輯器的時候,實際上是在編輯他的***Css Style***,去改變文字大小、顏色等外觀。 ![](https://i.imgur.com/JDXcKoE.png) Summernote 使用上非常容易,搭配jquery的selector就可以很快成功有一個編輯器介面可以用: ``` html <div id="summernote"></div> ``` ``` js $('#summernote').summernote(); ``` ### 圖片上傳流程解析: 要能夠在編輯器裡面上傳並插入圖片,大致上有兩個關鍵步驟: 1. 使用者選擇要上傳的圖片 2. 上傳完畢,拿回圖片網址,並將圖片插入目前游標位置 我們可以看到在上述編輯器裡面有個圖片上傳按鈕,以Web以及Javascript的角度來思考的話,**點擊該按鈕應該會有一個callback**,就算沒有我們也可以自己實作一個,不過既然Summernote預設就有這個按鈕,我猜想應該會有一個點擊上傳圖片後的hook,可以自己寫callback來決定使用者選擇圖片後,要做什麼動作。 果不其然在官方文件被我找到這個 onImageUpload 的hook: ![](https://i.imgur.com/eYl0rcl.png) 在callback參數裡面可以拿到使用者選擇的檔案,只要在這個callback裡面利用ajax進行圖檔上傳的動作,就可以順利上傳了,甚至在文件裡還有提供插入圖片到游標位置的方法: ```js // upload image to server and create imgNode... $summernote.summernote('insertNode', imgNode); ``` 既然有了方法,就可以整理一下圖片上傳的流程: ``` flow st=>start: Summernote選擇圖片 cb=>start: 圖片透過ajax上傳 saveImg=>start: 圖片儲存至Server(或cdn) saveInfo=>start: 儲存圖片相關資料至資料庫 getInfo=>start: 拿回圖片位址並回傳(從資料庫或cdn callback) insertImg=>end: 將拿回圖片位址放入<img/>並插入編輯器游標位置 st->cb->saveImg->saveInfo->getInfo->insertImg ``` ### 實際程式碼: jquery ajax圖片上傳: ```js function imageUpload(files){ let formData = new FormData(); formData.append('upload', files[0]); return $.ajax({ type: "POST", url: '/upload', data:formData, beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))}, cache : false, contentType : false, processData : false, }); } ``` 我把ajax內容拆了出來,把資料用參數的方式傳遞,以免每次上傳都要重寫一次: callback 內容 ```js $('#summernote').summernote( { height: 300, callbacks: { onImageUpload: function(files) { imageUpload(files).done((data, textStatus, jqXHR)=>{ let url = "/uploads/"+data.imageUrl $('#summernote').summernote('insertImage', url, 'newimage'); }) }, } }); ```

Import from clipboard

Paste your markdown or webpage here...

Advanced permission required

Your current role can only read. Ask the system administrator to acquire write and comment permission.

This team is disabled

Sorry, this team is disabled. You can't edit this note.

This note is locked

Sorry, only owner can edit this note.

Reach the limit

Sorry, you've reached the max length this note can be.
Please reduce the content or divide it to more notes, thank you!

Import from Gist

Import from Snippet

or

Export to Snippet

Are you sure?

Do you really want to delete this note?
All users will lose their connection.

Create a note from template

Create a note from template

Oops...
This template has been removed or transferred.
Upgrade
All
  • All
  • Team
No template.

Create a template

Upgrade

Delete template

Do you really want to delete this template?
Turn this template into a regular note and keep its content, versions, and comments.

This page need refresh

You have an incompatible client version.
Refresh to update.
New version available!
See releases notes here
Refresh to enjoy new features.
Your user state has changed.
Refresh to load new user state.

Sign in

Forgot password

or

By clicking below, you agree to our terms of service.

Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
Wallet ( )
Connect another wallet

New to HackMD? Sign up

Help

  • English
  • 中文
  • Français
  • Deutsch
  • 日本語
  • Español
  • Català
  • Ελληνικά
  • Português
  • italiano
  • Türkçe
  • Русский
  • Nederlands
  • hrvatski jezik
  • język polski
  • Українська
  • हिन्दी
  • svenska
  • Esperanto
  • dansk

Documents

Help & Tutorial

How to use Book mode

Slide Example

API Docs

Edit in VSCode

Install browser extension

Contacts

Feedback

Discord

Send us email

Resources

Releases

Pricing

Blog

Policy

Terms

Privacy

Cheatsheet

Syntax Example Reference
# Header Header 基本排版
- Unordered List
  • Unordered List
1. Ordered List
  1. Ordered List
- [ ] Todo List
  • Todo List
> Blockquote
Blockquote
**Bold font** Bold font
*Italics font* Italics font
~~Strikethrough~~ Strikethrough
19^th^ 19th
H~2~O H2O
++Inserted text++ Inserted text
==Marked text== Marked text
[link text](https:// "title") Link
![image alt](https:// "title") Image
`Code` Code 在筆記中貼入程式碼
```javascript
var i = 0;
```
var i = 0;
:smile: :smile: Emoji list
{%youtube youtube_id %} Externals
$L^aT_eX$ LaTeX
:::info
This is a alert area.
:::

This is a alert area.

Versions and GitHub Sync
Get Full History Access

  • Edit version name
  • Delete

revision author avatar     named on  

More Less

Note content is identical to the latest version.
Compare
    Choose a version
    No search result
    Version not found
Sign in to link this note to GitHub
Learn more
This note is not linked with GitHub
 

Feedback

Submission failed, please try again

Thanks for your support.

On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

Please give us some advice and help us improve HackMD.

 

Thanks for your feedback

Remove version name

Do you want to remove this version name and description?

Transfer ownership

Transfer to
    Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

      Link with GitHub

      Please authorize HackMD on GitHub
      • Please sign in to GitHub and install the HackMD app on your GitHub repo.
      • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
      Learn more  Sign in to GitHub

      Push the note to GitHub Push to GitHub Pull a file from GitHub

        Authorize again
       

      Choose which file to push to

      Select repo
      Refresh Authorize more repos
      Select branch
      Select file
      Select branch
      Choose version(s) to push
      • Save a new version and push
      • Choose from existing versions
      Include title and tags
      Available push count

      Pull from GitHub

       
      File from GitHub
      File from HackMD

      GitHub Link Settings

      File linked

      Linked by
      File path
      Last synced branch
      Available push count

      Danger Zone

      Unlink
      You will no longer receive notification when GitHub file changes after unlink.

      Syncing

      Push failed

      Push successfully