copy & paste to upload image

The original post was posted in my blog copy & paste to upload image

I really love that in 簡(jiǎn)書(shū) I can copy & paste to upload image in the markdown editor. I'm going to implement it for my blog as well.

Paste event

<textarea @paste="handlePaste"></textarea>

HTML elements support paste event (see doc). In the callback you can access the clipboardData.

methods: {
    handlePaste(e) {
      for (let i = 0; i < e.clipboardData.items.length; ++i) {
        let item = e.clipboardData.items[i];
        console.log("kind:", item.kind, "type:", item.type);
      }
    }
}

Each of the item is an instance of DataTransferItem (see doc).

It has two read-only properties:

  1. kind: The kind of data item, string or file.
  2. type: The data item's type, typically a MIME type.

When you paste an image into the textarea, you will get the following log:

kind: string type: text/plain
kind: file type: image/png

The text item is the name of the file, while the image item is the image content.

When pasting an image, the default behavior of Chrome pastes the file name as text. To prevent this default behavior, call e.preventDefault() in handlePaste.

Read data and upload

Image

For image, we need to use getAsFile API (see doc).

if (item.kind == "file" && item.type.startsWith("image/")) {
  this.uploadImage(item.getAsFile());
}

As for how to upload image, please read my post about this.

The file you get from getAsFile is something like this:

Some issues:

  1. the MIME type is always image/png even though I uploaded a JPEG.
  2. the file name is always image.png. The actual file name needs to be read by APIs shown below.
  3. the namefield is readonly. If you change it directly you will get exception Cannot assign to read only property 'name' of object '#<File>'. As a workaround, you can create a copy of the file and assign a new name (see reference)
const file = item.getAsFile();
const name = e.clipboardData.getData("text");
this.uploadImage(new File([file], name, { type: file.type }));

Text

For text, we have two options, getAsString and getData.

getAsString

The first option is getAsString API (see doc). You need to access the data in the callback.

if (item.kind === "string" && item.type.startsWith("text/plain")) {
  item.getAsString(s => {
    console.log(s);
  });
}

getData

The second options is to use getData (see doc).

e.clipboardData.getData("text")

It requires a format parameter which is a DOMString representing the type of data to retrieve.

Insert text

In the doc for paste event, it has an example of pasting text between divs.

In my case, I want to paste the markdown into the textarea.

selectionStart and selectionEnd

In the doc of HTMLTextAreaElement, we can see it has selectionStart and selectionEnd fields which can be used to get the selection range.

So my first attemp was to use these two fields to inject the markdown string.

service.uploadImage(new File([file], name, { type: file.type })).then(uploaded => {
  let textarea = e.target;
  const start = textarea.selectionStart;
  const end = textarea.selectionEnd;
  const paste = `![${uploaded.originalname}](${location.origin}${uploaded.path})`;
  this.post.content = stringSplice(this.post.content, start, end - start, paste);
});

This has two issues:

  1. After pasting, the cursor is moved to the end of the content. I want to keep the cursor around the pasted text.
  2. You can' use Ctrl+Z to undo the pasting.

setRangeText

My second attemp was using the setRangeText API (see doc).

const textarea = e.target;
textarea.setRangeText(contentToPaste);

Now after pasting the cursor is at the begining of the range text. But I still can't undo the pasting.

execCommand

Learnt from fregante/insert-text-textarea, you can simple use the following line to insert the text. This works in Chrome and also has Undo support.

const textarea = e.target;
textarea.focus();
document.execCommand("insertText", false, contentToPaste);

Since uploading image is an asynchronous job, we can't guarantee the focus is still in the textarea when we do execCommand. So don't forget to add textarea.focus() before calling execCommand.

Set selection range

Just like the UX in 簡(jiǎn)書(shū), I want to select the name part of the image in the markdown line so as to make it easier for the user to rename the image. We can simply call textarea.selectSelectionRange(start, end) after executing the insert command (see doc)

Summary

handlePaste(e) {
  for (let i = 0; i < e.clipboardData.items.length; ++i) {
    let item = e.clipboardData.items[i];
    if (item.kind == "file" && item.type.startsWith("image/")) {
      this.uploadImageStatus = RequestStatus.Pending;
      e.preventDefault();
      const textarea = e.target;
      textarea.disabled = true;
      const file = item.getAsFile();
      const name = e.clipboardData.getData("text");
      service.uploadImage(new File([file], name, { type: file.type })).then(uploaded => {
        const paste = `![${name}](${location.origin}${uploaded.path})`;
        const start = textarea.selectionStart + 2;
        textarea.disabled = false;
        textarea.focus();
        document.execCommand("insertText", false, paste);
        textarea.setSelectionRange(start, start + name.length);
        this.uploadImageStatus = RequestStatus.Success;
      });
    }
  }
}

Note that the user might move their cursor during upload, which might cause the image to be inserted at another place than the place where he/she pasted the image.

簡(jiǎn)書(shū) does allow the user to move their cursor arbitrarily and have the text inserted at the correct place.

In the above code I simply disable the textarea and show an overlay during the upload.

Lastly, the screenshot of the UX is as follows.

upload image experience

Reference

  1. Upload Image by Copy and Paste
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末虑瀑,一起剝皮案震驚了整個(gè)濱河市民逼,隨后出現(xiàn)的幾起案子臼节,更是在濱河造成了極大的恐慌评凝,老刑警劉巖狞膘,帶你破解...
    沈念sama閱讀 216,324評(píng)論 6 498
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件讯蒲,死亡現(xiàn)場(chǎng)離奇詭異掸鹅,居然都是意外死亡童谒,警方通過(guò)查閱死者的電腦和手機(jī)单旁,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,356評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門(mén),熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)饥伊,“玉大人象浑,你說(shuō)我怎么就攤上這事±哦梗” “怎么了愉豺?”我有些...
    開(kāi)封第一講書(shū)人閱讀 162,328評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)茫因。 經(jīng)常有香客問(wèn)我蚪拦,道長(zhǎng),這世上最難降的妖魔是什么节腐? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,147評(píng)論 1 292
  • 正文 為了忘掉前任外盯,我火速辦了婚禮,結(jié)果婚禮上翼雀,老公的妹妹穿的比我還像新娘饱苟。我一直安慰自己,他們只是感情好狼渊,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,160評(píng)論 6 388
  • 文/花漫 我一把揭開(kāi)白布箱熬。 她就那樣靜靜地躺著,像睡著了一般狈邑。 火紅的嫁衣襯著肌膚如雪城须。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 51,115評(píng)論 1 296
  • 那天米苹,我揣著相機(jī)與錄音糕伐,去河邊找鬼。 笑死蘸嘶,一個(gè)胖子當(dāng)著我的面吹牛良瞧,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播训唱,決...
    沈念sama閱讀 40,025評(píng)論 3 417
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼褥蚯,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了况增?” 一聲冷哼從身側(cè)響起赞庶,我...
    開(kāi)封第一講書(shū)人閱讀 38,867評(píng)論 0 274
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后歧强,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體澜薄,經(jīng)...
    沈念sama閱讀 45,307評(píng)論 1 310
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,528評(píng)論 2 332
  • 正文 我和宋清朗相戀三年誊锭,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了表悬。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,688評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡丧靡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出籽暇,到底是詐尸還是另有隱情温治,我是刑警寧澤,帶...
    沈念sama閱讀 35,409評(píng)論 5 343
  • 正文 年R本政府宣布戒悠,位于F島的核電站熬荆,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏绸狐。R本人自食惡果不足惜卤恳,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,001評(píng)論 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望寒矿。 院中可真熱鬧突琳,春花似錦、人聲如沸符相。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,657評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)啊终。三九已至镜豹,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間蓝牲,已是汗流浹背趟脂。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 32,811評(píng)論 1 268
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留例衍,地道東北人昔期。 一個(gè)月前我還...
    沈念sama閱讀 47,685評(píng)論 2 368
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像肄渗,于是被迫代替她去往敵國(guó)和親镇眷。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,573評(píng)論 2 353