国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

Nodejs+angularjs結(jié)合multiparty實(shí)現(xiàn)多圖片上傳的示例代碼

2019-11-19 15:15:38
字體:
供稿:網(wǎng)友

這次我們說一下nodejs+angularjs多圖片上傳的問題

此前也在網(wǎng)站看了很多篇文章,有關(guān)的內(nèi)容說多不多,說少也不少,但我一一試過以后有成功的,也有沒有成功的,折磨了我很長時(shí)間,最終也是成功實(shí)現(xiàn)了,于是想寫下這篇文章,分享我的代碼,也希望后人不要踏進(jìn)我的坑。

首先說一下nodejs所以依賴的插件 multiparty 和 fs,可以用npm工具來安裝

npm install multiparty --save npm install fs --save 

先貼出我nodejs的后臺(tái)代碼(注意:我的后臺(tái)代碼是寫在路由中的)

const express = require('express')const multiparty = require('multiparty');const fs = require('fs');const router = express.Router();router.post('/uploadImg', function (req, res,next) { //生成multiparty對象,并配置上傳目標(biāo)路徑 var form = new multiparty.Form({ uploadDir: './public/uploads/',//路徑需要對應(yīng)自己的項(xiàng)目更改 /*設(shè)置文件保存路徑 */ encoding: 'utf-8', /*編碼設(shè)置 */ maxFilesSize: 20000 * 1024 * 1024, /*設(shè)置文件最大值 20MB */ keepExtensions: true, /*保留后綴*/ });  //上傳處理 form.parse(req, function(err, fields, files) {  var filesTmp = JSON.stringify(files, null, 2);  console.log(files);    function isType(str) {   if (str.indexOf('.') == -1) {    return '-1';   } else {    var arr = str.split('.');    return arr.pop();   }  }    if (err) {   console.log('parse error: ' + err);  } else {  var inputFile = files.image[0];  var uploadedPath = inputFile.path;  var type = isType(inputFile.originalFilename);  /*var dstPath = './public/files/' + inputFile.originalFilename;//真實(shí)文件名*/  var name = new Date().getTime() + '.' + type; /*以上傳的時(shí)間戳命名*/  var dstPath = './public/uploads/' + name; /*路徑需要對應(yīng)自己的項(xiàng)目更改*/  console.log("type---------" + type);    if (type == "jpg" || type == "png" || type == "exe") {   console.log('可以上傳');   //重命名為真實(shí)文件名   fs.rename(uploadedPath, dstPath, function(err) {    if (err) {     console.log('rename error: ' + err);    } else {     console.log('上傳成功');    }   });   res.writeHead(200, { 'content-type': 'text/plain;charset=utf-8' });   var data = { "code": "1",'result_code':'SUCCESS', "msg": "上傳成功", "results": [{ "name": name, "path": "uploads/" + name }] };   console.log(JSON.stringify(data))   res.end(JSON.stringify(data));      } else {    fs.unlink(uploadedPath, function(err) {    if (err) {    return console.error(err);    }    console.log("文件刪除成功!");    });        console.log('不能上傳' + inputFile.originalFilename);    res.writeHead(200, { 'content-type': 'text/plain;charset=utf-8' });    var data = { "code": 0, "msg": "上傳失敗" };    res.end(JSON.stringify(data));      }  }   });}); 

然后是angularjs的控制器代碼

appIndex.controller('createImgs',function($rootScope,$scope,$http){  // 圖片上傳  $scope.reader = new FileReader();  //創(chuàng)建一個(gè)FileReader接口  $scope.form = {   //用于綁定提交內(nèi)容,圖片或其他數(shù)據(jù)    image:{},  };  $scope.thumb = {};   //用于存放圖片的base64  $scope.thumb_default = {  //用于循環(huán)默認(rèn)的‘加號(hào)'添加圖片的框    1111:{}  };  $scope.img_upload = function(files) {    //單次提交圖片的函數(shù)    $scope.guid = (new Date()).valueOf();  //通過時(shí)間戳創(chuàng)建一個(gè)隨機(jī)數(shù),作為鍵名使用    $scope.reader.readAsDataURL(files[0]); //FileReader的方法,把圖片轉(zhuǎn)成base64    $scope.reader.onload = function(ev) {      $scope.$apply(function(){        $scope.thumb[$scope.guid] = {          imgSrc : ev.target.result, //接收base64        }      });    };        var data = new FormData();   //以下為像后臺(tái)提交圖片數(shù)據(jù)    data.append('image', files[0]);    data.append('guid',$scope.guid);    $http({      method: 'post',      url: '/uploadImg',      data:data,      headers: {'Content-Type': undefined},      transformRequest: angular.identity    }).then(function successCallBack(response) {      if (response.data.result_code == 'SUCCESS') {        $scope.form.image[$scope.guid] = response.data.results[0].path;        $scope.thumb[$scope.guid].status = 'SUCCESS';        console.log($scope.form)      }      if(data.result_code == 'FAIL'){        console.log(data)      }    }, function errorCallback(response) {      console.log('網(wǎng)絡(luò)錯(cuò)誤')    })  };  $scope.img_del = function(key) {  //刪除,刪除的時(shí)候thumb和form里面的圖片數(shù)據(jù)都要?jiǎng)h除,避免提交不必要的    var guidArr = [];    for(var p in $scope.thumb){      guidArr.push(p);    }    delete $scope.thumb[guidArr[key]];    delete $scope.form.image[guidArr[key]];  };  $scope.submit_form = function(){  //圖片選擇完畢后的提交,這個(gè)提交并沒有提交前面的圖片數(shù)據(jù),只是提交用戶操作完畢后,到底要上傳哪些,通過提交鍵名或者鏈接,后臺(tái)來判斷最終用戶的選擇,整個(gè)思路也是如此    $http({      method: 'post',      url: '/insertImg',      data:$scope.form,    }).success(function(data) {      console.log(data);      })  };  }) 

最后是html代碼

<div class="col-md-12 col-lg-7 fill">  <div class="form-group">    <h4>圖片</h4>    <p>支持批量上傳,支持照片的格式為<span class="label label-default">jpg & png</span> 。每張照片請不要超過<span class="label label-default">50M</span> 。為了在全屏下獲得最好的效果,照片的分辨率最好大于<span class="label label-default">1920 x 1280</span> 。上傳后的照片默認(rèn)會(huì)按照它們的EXIF日期來排序。</p>    <div ng-repeat="item in thumb_default">      <!-- 這里之所以寫個(gè)循環(huán),是為了后期萬一需要多個(gè)‘加號(hào)'框 -->      <label for="one-input">        <div class="add">          <span></span>          <span></span>        </div>      </label>      <input type="file" id="one-input" accept="image/*" file-model="images" onchange="angular.element(this).scope().img_upload(this.files)"/>    </div>  </div>  <div class="hr-text hr-text-left m-b-1 m-t-1">    <h6 class="text-white">      <strong>已上傳</strong>    </h6>  </div>  <div ng-repeat="item in thumb" class="imgload">  <!-- 采用angular循環(huán)的方式,對存入thumb的圖片進(jìn)行展示 -->    <label>      ![]({{item.imgSrc}})    </label>    <div class="imgDel">      <span ng-if="item.imgSrc" ng-click="img_del($index)" class="glyphicon glyphicon-remove"></span>    </div>      </div>  </div> 

添加css樣式以便頁面更加合理美觀

.fill .form-group label .add{  border:1px solid #666;  width: 100px;  height: 100px;  position: relative;  cursor: pointer;}.fill .form-group label .add span:nth-of-type(1){  width: 2px;  height: 50px;  display: block;  position: absolute;  left: 50%;  top: 50%;  margin-top: -25px;  margin-left: -1px;  background: #666;}.fill .form-group label .add span:nth-of-type(2){  background: #666;  width: 50px;  height: 2px;  display: block;  position: absolute;  left: 50%;  top: 50%;  margin-top: -1px;  margin-left: -25px;}.fill .form-group input{  display: none;}.fill .imgload{  display: inline-block;  margin: 7px;  position: relative;}.fill .imgload label img{  width: 200px;  height: 200px;}.fill .imgload .imgDel{  width:20px;  height: 20px;  background: #666;  border-radius: 50%;  position: absolute;  right: -10px;  top: -10px;  color: #ccc;  text-align: center;  line-height: 20px;  cursor: pointer;} 

注:整體頁面采用bootstrap框架布局

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

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 靖安县| 虹口区| 将乐县| 三河市| 永和县| 五常市| 临潭县| 安阳县| 同心县| 陇西县| 横峰县| 田东县| 寿光市| 鄢陵县| 磐安县| 龙游县| 吉木乃县| 十堰市| 麻城市| 桐乡市| 台中县| 聂荣县| 莒南县| 洛隆县| 涞源县| 封丘县| 册亨县| 延寿县| 巴东县| 武清区| 安丘市| 五莲县| 闽侯县| 平度市| 文水县| 常宁市| 江油市| 浦江县| 华容县| 五指山市| 如东县|