最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

vue+node實(shí)現(xiàn)圖片上傳及預(yù)覽的示例方法

 更新時間:2018年11月22日 11:01:13   作者:杜鑫鴨  
這篇文章主要介紹了vue+node實(shí)現(xiàn)圖片上傳及預(yù)覽的示例方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

本文介紹了vue+node實(shí)現(xiàn)圖片上傳及預(yù)覽的示例方法,分享給大家,具體如下:

先上效果圖


上代碼

html部分主要是借助了weui的樣式

<template>
 <div>
  <myheader :title="'發(fā)布動態(tài)'">
   <i class="iconfont icon-fanhui1 left" slot="left" @click="goback"></i>
  </myheader>
  <div class="upload">
   <div v-if="userInfo._id">
    <!--圖片上傳-->
    <div class="weui-gallery" id="gallery">
     <span class="weui-gallery__img" id="galleryImg"></span>
     <div class="weui-gallery__opr">
      <a href="javascript:" rel="external nofollow" class="weui-gallery__del">
       <i class="weui-icon-delete weui-icon_gallery-delete"></i>
      </a>
     </div>
    </div>
    <div class="weui-cells weui-cells_form">
     <div class="weui-cell">
      <div class="weui-cell__bd">
       <textarea class="weui-textarea" v-model="content" placeholder="你想說啥" rows="3"></textarea>
      </div>
     </div>
     <div class="weui-cell">
      <div class="weui-cell__bd">
       <div class="weui-uploader">
        <div class="weui-uploader__bd">
         <ul class="weui-uploader__files" id="uploaderFiles">
          <li ref="files" class="weui-uploader__file" v-for="(image,index) in images" :key="index"
            :style="'backgroundImage:url(' + image +' )'"><span @click="deleteimg(index)" class="x">&times;</span></li>
         </ul>
         <div v-show="images.length < maxCount" class="weui-uploader__input-box">
          <input @change="change" id="uploaderInput" class="weui-uploader__input " type="file"
             multiple accept="image/*">
         </div>
        </div>
       </div>
      </div>
     </div>
    </div>
    <a class="weui-btn weui-btn_primary btn-put" style="margin: 20px " @click.prevent.once="put">發(fā)送</a>
   </div>
   <unlogin v-else> </unlogin>
  </div>
 </div>
</template>

重點(diǎn)部分在于

<ul class="weui-uploader__files" id="uploaderFiles">
 <li ref="files" class="weui-uploader__file" v-for="(image,index) in images" :key="index"
   :style="'backgroundImage:url(' + image +' )'"><span @click="deleteimg(index)" class="x">&times;</span></li>
</ul>
<div v-show="!this.$refs.files||this.$refs.files.length < maxCount" class="weui-uploader__input-box">
 <input @change="change" id="uploaderInput" class="weui-uploader__input" type="file"
     multiple accept="image/*">
</div>

通過@change="change"監(jiān)聽圖片的上傳,把圖片轉(zhuǎn)成base64后(后面會講怎么轉(zhuǎn)base64)將base64的地址加入到images數(shù)組,通過v-for="(image,index) in images"把要上傳的圖片在頁面中顯示出來,即達(dá)到了預(yù)覽的效果

js部分

data部分

data() {
   return {
    content: '',//分享動態(tài)的文字內(nèi)容
    maxSize: 10240000 / 2,//圖片的最大大小
    maxCount: 8,//最大數(shù)量
    filesArr: [],//保存要上傳圖片的數(shù)組
    images: []//轉(zhuǎn)成base64后的圖片的數(shù)組
   }
  }

delete方法

deleteimg(index) {
    this.filesArr.splice(index, 1);
    this.images.splice(index, 1);
   }

change方法

change(e) {
    let files = e.target.files;
    // 如果沒有選中文件,直接返回
    if (files.length === 0) {
     return;
    }
    if (this.images.length + files.length > this.maxCount) {
     Toast('最多只能上傳' + this.maxCount + '張圖片!');
     return;
    }
    let reader;
    let file;
    let images = this.images;
    for (let i = 0; i < files.length; i++) {
     file = files[i];
     this.filesArr.push(file);
     reader = new FileReader();
     if (file.size > self.maxSize) {
      Toast('圖片太大,不允許上傳!');
      continue;
     }
     reader.onload = (e) => {
      let img = new Image();
      img.onload = function () {
       let canvas = document.createElement('canvas');
       let ctx = canvas.getContext('2d');
       let w = img.width;
       let h = img.height;
       // 設(shè)置 canvas 的寬度和高度
       canvas.width = w;
       canvas.height = h;
       ctx.drawImage(img, 0, 0, w, h);
       let base64 = canvas.toDataURL('image/png');
       images.push(base64);
      };
      img.src = e.target.result;
     };
     reader.readAsDataURL(file);
    }
   }

put方法把filesArr中保存的圖片通過axios發(fā)送到后端,注意要設(shè)置headers信息

put() {
    Indicator.open('發(fā)布中...');
    let self = this;
    let content = this.content;
    let param = new FormData();
    param.append('content', content);
    param.append('username', this.userInfo._id);
    this.filesArr.forEach((file) => {
     param.append('file2', file);
    });
    self.axios.post('/upload/uploadFile', param, {
     headers: {
      "Content-Type": "application/x-www-form-urlencoded"
     }
    }).then(function (result) {
     console.log(result.data);
     self.$router.push({path: '/home'});
     Indicator.close();
     Toast(result.data.msg)
    })
   }

后端通過multer模塊保存?zhèn)鬏數(shù)膱D片,再把保存下來的圖片發(fā)送到阿里云oss(這個可以根據(jù)自己的使用情況變化)

let filePath;
let fileName;

let Storage = multer.diskStorage({
  destination: function (req, file, cb) {//計算圖片存放地址
    cb(null, './public/img');
  },
  filename: function (req, file, cb) {//圖片文件名
    fileName = Date.now() + '_' + parseInt(Math.random() * 1000000) + '.png';
    filePath = './public/img/' + fileName;
    cb(null, fileName)
  }
});
let upload = multer({storage: Storage}).any();//file2表示圖片上傳文件的key

router.post('/uploadFile', function (req, res, next) {
  upload(req, res, function (err) {
    let content = req.body.content || '';
    let username = req.body.username;
    let imgs = [];//要保存到數(shù)據(jù)庫的圖片地址數(shù)組
    if (err) {
      return res.end(err);
    }
    if (req.files.length === 0) {
      new Pyq({
        writer: username,
        content: content
      }).save().then((result) => {
        res.json({
          result: result,
          code: '0',
          msg: '上傳成功'
        });
      })
    }
    /*client.delete('public/img/1.png', function (err) {
      console.log(err)
    });*/
    let i = 0;
    req.files.forEach((item, index) => {
      let filePath = `./public/img/${item.filename}`;
      put(item.filename,filePath,(result)=>{
        imgs.push(result.url);
        i++;
        if (i === req.files.length) {
        //forEach循環(huán)是同步的,但上傳圖片是異步的,所以用一個i去標(biāo)記圖片是否全部上傳成功
        //這時才把數(shù)據(jù)保存到數(shù)據(jù)庫
          new Pyq({
            content: content,
            writer: username,
            pimg: imgs
          }).save().then(() => {
            res.json({
              code: '0',
              msg: '發(fā)布成功'
            });
          })
        }
      })
    })
  })
});

github地址

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • vue3 ref 和reactive的區(qū)別詳解

    vue3 ref 和reactive的區(qū)別詳解

    本文主要介紹了vue3 ref 和reactive的區(qū)別詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-03-03
  • vue升級之路之vue-router的使用教程

    vue升級之路之vue-router的使用教程

    自動安裝的vue-router,會在src 文件夾下有個一個 router -> index.js 文件 在 index.js 中創(chuàng)建 routers 對象,引入所需的組件并配置路徑。這篇文章主要介紹了vue-router的使用,需要的朋友可以參考下
    2018-08-08
  • window.onresize在vue中只能使用一次,自適應(yīng)resize報錯問題

    window.onresize在vue中只能使用一次,自適應(yīng)resize報錯問題

    這篇文章主要介紹了window.onresize在vue中只能使用一次,自適應(yīng)resize報錯問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-10-10
  • Vue導(dǎo)航守衛(wèi)使用教程詳解

    Vue導(dǎo)航守衛(wèi)使用教程詳解

    這篇文章主要介紹了Vue導(dǎo)航守衛(wèi)使用教程,可以向任意給定的導(dǎo)航守衛(wèi)傳遞next,但是next的使用過程容易出錯,需要確保next在任何給定的導(dǎo)航守衛(wèi)中都被嚴(yán)格調(diào)用一次
    2023-04-04
  • vue router路由嵌套不顯示問題的解決方法

    vue router路由嵌套不顯示問題的解決方法

    這篇文章主要為大家詳細(xì)介紹了vue router路由嵌套不顯示的問題,具有一定的參考價值,感興趣的小伙伴們可以參考一下vue-router 路由嵌套不顯示問題
    2017-06-06
  • vue項目打包后請求地址錯誤/打包后跨域操作

    vue項目打包后請求地址錯誤/打包后跨域操作

    這篇文章主要介紹了vue項目打包后請求地址錯誤/打包后跨域操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-11-11
  • 在vue中獲取token,并將token寫進(jìn)header的方法

    在vue中獲取token,并將token寫進(jìn)header的方法

    今天小編就為大家分享一篇在vue中獲取token,并將token寫進(jìn)header的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-09-09
  • Pinia介紹及工作原理解析

    Pinia介紹及工作原理解析

    這篇文章主要為大家介紹了Pinia介紹及工作原理解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-03-03
  • Vue3中Props和Emit的工作原理詳解

    Vue3中Props和Emit的工作原理詳解

    在現(xiàn)代前端開發(fā)中,Vue.js 來作為一個流行的 JavaScript 框架,提供了簡單易用的 API 和強(qiáng)大的功能,在 Vue 3 中,“Props”和“Emit”是兩個核心概念,本文將詳細(xì)探討這兩個概念的工作原理,并提供示例代碼以幫助更好地理解它們的使用,需要的朋友可以參考下
    2024-11-11
  • vue修改Element的el-table樣式的4種方法

    vue修改Element的el-table樣式的4種方法

    這篇文章主要介紹了vue修改Element的el-table樣式的4種方法,幫助大家更好的理解和使用vue,感興趣的朋友可以了解下
    2020-09-09

最新評論

灵川县| 长治县| 三穗县| 运城市| 象州县| 平果县| 靖安县| 怀仁县| 昌吉市| 镇宁| 肇庆市| 马公市| 临桂县| 高邮市| 奉新县| 抚顺市| 哈密市| 河间市| 安阳县| 三江| 镇赉县| 邓州市| 加查县| 安多县| 拉萨市| 宁强县| 米林县| 龙游县| 益阳市| 平乐县| 滨州市| 广州市| 松溪县| 安徽省| 南靖县| 鹿泉市| 武胜县| 嵊州市| 隆化县| 潮安县| 新民市|