Home  >  Article  >  Web Front-end  >  vue-simplemde implements image drag and paste function (code attached)

vue-simplemde implements image drag and paste function (code attached)

php中世界最好的语言
php中世界最好的语言Original
2018-04-28 13:59:502670browse

This time I will bring you vue-simplemde to implement the image drag-and-drop function (with code). What are the precautions for vue-simplemde to implement the image drag-and-paste function. The following is a practical case. One Get up and take a look.

The project uses the vue framework and needs a markdown editing box. I searched for it on npm and found that simplemde is quite good. Since I am lazy, I searched again on npm and found it. vue-simplemdeThis package, then start using it.

But thisvue-simplemde does not support drag-and-drop upload and paste upload of images. It cannot be said that it is because of vue-simplemde, because vue-simplemde only encapsulates simplemde into a Vue plugin. So in the end, it is because simplemde does not provide relevant functions, but for the sake of user experience, this function is necessary unless the markdown editor is not used. Instead, use a rich text editor. In that case, a lot of code in the project will have to be changed. So I checked articles online and some codes on github. The following will be analyzed

Drag and drop

The core of the drag and drop API is the drop event, which is when we drag a file from the desktop to The name of the event that is triggered when the browser is released.

We all know that if you drag a picture into the browser, the picture will be opened directly. This is because the browser defaults to opening the file when you drag the file into the browser. Therefore, We need to prevent native operations.

Let’s write a piece of code now to block the default event

window.addEventListener("drop", e => {
 e = e || event
 if (e.target.className === 'CodeMirror-scroll') { // 如果进入到编辑器的话,将阻止默认事件
 e.preventDefault()
 }
}, false)

CodeMirror-scroll This Class is the Class name of the simplemde edit box.

Now we drag the file into this edit box and then release it, nothing will happen. If it is outside the edit box, the default event will still be triggered.

The following is to get the simplemde method and give it the drop Event handling method.

// 假设页面一共有三个编辑窗口,所以需要循环监听事件
[ this.$refs.simplemde1,
 this.$refs.simplemde2,
 this.$refs.simplemde3
].map(({simplemde}) => {
 simplemde.codemirror.on('drop', (editor, e) => {
 if (!(e.dataTransfer && e.dataTransfer.files)) {
  // 弹窗说明,此浏览器不支持此操作
  return
 }
 let dataList = e.dataTransfer.files
 let imageFiles = [] // 要上传的文件实例数组
 // 循环,是因为可能会同时拖动几个图片文件
 for (let i = 0; i < dataList.length; i++) {
 // 如果不是图片,则弹窗警告 仅支持拖拽图片文件
  if (dataList[i].type.indexOf(&#39;image&#39;) === -1) {
  // 下面的continue,作用是,如果用户同时拖动2个图片和一个文档,那么文档不给于上传,图片照常上传。
  continue
  }
  imageFiles.push(dataList[i]) // 先把当前的文件push进数组里,等for循环结束之后,统一上传。
 }
 // uploadImagesFile方法是上传图片的方法
 // simplemde.codemirror的作用是用于区分当前的图片上传是处于哪个编辑框
 this.uploadImagesFile(simplemde.codemirror, imageFiles)
 // 因为已经有了下面这段代码,所以上面的屏蔽默认事件代码就不用写了
 e.preventDefault()
 })
})

At first glance, the code seems to be a bit too much. That is because of the comments. The following is the code without comments. You can have your own opinions and understanding based on the following code:

[ this.$refs.simplemde1,
 this.$refs.simplemde2,
 this.$refs.simplemde3
].map(({simplemde}) => {
 simplemde.codemirror.on('drop', (editor, e) => {
 if (!(e.dataTransfer && e.dataTransfer.files)) {
  return
 }
 let dataList = e.dataTransfer.files
 let imageFiles = []
 for (let i = 0; i < dataList.length; i++) {
  if (dataList[i].type.indexOf(&#39;image&#39;) === -1) {
  continue
  }
  imageFiles.push(dataList[i])
 }
 this.uploadImagesFile(simplemde.codemirror, imageFiles)
 e.preventDefault()
 })
})

Paste

The pasting API is the paste method, this is not like Same as above, there is no need to disable the default event for pasting, because we can see that when you copy an image and press ctrl v in the browser, nothing will change, so there is no need to disable the default event.

The following is the code:

simplemde.codemirror.on(&#39;paste&#39;, (editor, e) => { // 粘贴图片的触发函数
 if (!(e.clipboardData && e.clipboardData.items)) {
 // 弹窗说明,此浏览器不支持此操作
 return
 }
 try {
 let dataList = e.clipboardData.items
 if (dataList[0].kind === 'file' && dataList[0].getAsFile().type.indexOf('image') !== -1) {
  this.uploadImagesFile(simplemde.codemirror, [dataList[0].getAsFile()])
 }
 } catch (e) {
 // 弹窗说明,只能粘贴图片
 }
})

The reason why the try...catch method is written here is because if you paste it, if it is a file, items will be empty, and in In the if loop below, use dataList[0].kind. That is e.clipboardData.items[0].kind. When the item is empty and you access a non-existing kind attribute, an error will be reported. So here you need to use the try...catch method to judge.

dataList[0].getAsFile().type.indexOf('image') !== -1 This sentence is a judgment. The pasted thing is confirmed to be a picture and not something else. thing.

The difference between the uploaded images in if is [dataList[0].getAsFile()], because in order to unify the format and facilitate processing by the uploadImagesFile function, I added [] to make it an array. . dataList[0].getAsFile() is to get the file instance.

Upload

Uploading is a little troublesome:

uploadImagesFile (simplemde, files) {
 // 把每个文件实例使用FormData进行包装一下,然后返回一个数组
 let params = files.map(file => {
 let param = new FormData()
 param.append('file', file, file.name)
 return param
 })
 let makeRequest = params => {
 return this.$http.post('/Api/upload', params)
 }
 let requests = params.map(makeRequest)
 this.$http.spread = callback => {
 return arr => {
  return callback.apply(null, arr)
 }
 }
 // 服务端返回的格式是{state: Boolean, data: String}
 // state为false时,data就是返回的错误信息
 // state为true时,data是图片上传后url地址,这个地址是针对网站的绝对路径。如下:
 // /static/upload/2cfd6a50-3d30-11e8-b351-0d25ce9162a3.png
 Promise.all(requests)
 .then(this.$http.spread((...resps) => {
  for (let i = 0; i < resps.length; i++) {
  let {state, data} = resps[i].data
  if (!state) {
   // 弹窗显示data的错误信息
   continue
  }
  let url = `![](${location.origin + data})` // 拼接成markdown语法
  let content = simplemde.getValue()
  simplemde.setValue(content + url + &#39;\n&#39;) // 和编辑框之前的内容进行拼接
  }
 }))
}

Because I encapsulate axiox into a vue plug-in to use , this will cause this.$http to be instantiated, not itself. The solution suggested by the axios maintainer is to re-introduce the axios package and use it. But I don't think it's necessary. Internally axios.all is Promise.all . The implementation code of axios.spread is relatively small, so just take it and reassign it to axios.

So the code above is

Promise.all(requests)
 .then(this.$http.spread((...resps) => {
 // code
 })

Translate this code and it will be

axios.all(requests)
 .then(axios.spread((...resps) => {
 // code
 })

Regarding this issue, please read the official explanation: axios-all-is-not-a-function-inside-vue-component. You can also take a look at the code of axios: axios.js#L45-L48

I won’t delve into this issue for the time being. Let’s return to the topic just now.

I mentioned above that when state is true, data is the absolute path of the file relative to the website, such as: /static/upload/2cfd6a50-3d30-11e8-b351-0d25ce9162a3.png

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

jQuery encoding conversion base64 upload through AJAX

vue component writing specification

The above is the detailed content of vue-simplemde implements image drag and paste function (code attached). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn