溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Nodejs+angularjs結(jié)合multiparty如何實現(xiàn)多圖片上傳

發(fā)布時間:2021-07-22 14:31:13 來源:億速云 閱讀:228 作者:小新 欄目:web開發(fā)

小編給大家分享一下Nodejs+angularjs結(jié)合multiparty如何實現(xiàn)多圖片上傳,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!

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

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

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

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

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

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)自己的項目更改
 /*設(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;//真實文件名*/
  var name = new Date().getTime() + '.' + type; /*以上傳的時間戳命名*/
  var dstPath = './public/uploads/' + name; /*路徑需要對應(yīng)自己的項目更改*/
  console.log("type---------" + type);
  
  if (type == "jpg" || type == "png" || type == "exe") {
   console.log('可以上傳');
   //重命名為真實文件名
   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)建一個FileReader接口
  $scope.form = {   //用于綁定提交內(nèi)容,圖片或其他數(shù)據(jù)
    image:{},
  };
  $scope.thumb = {};   //用于存放圖片的base64
  $scope.thumb_default = {  //用于循環(huán)默認的‘加號'添加圖片的框
    1111:{}
  };

  $scope.img_upload = function(files) {    //單次提交圖片的函數(shù)
    $scope.guid = (new Date()).valueOf();  //通過時間戳創(chuàng)建一個隨機數(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();   //以下為像后臺提交圖片數(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ò)錯誤')
    })
  };

  $scope.img_del = function(key) {  //刪除,刪除的時候thumb和form里面的圖片數(shù)據(jù)都要刪除,避免提交不必要的
    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(){  //圖片選擇完畢后的提交,這個提交并沒有提交前面的圖片數(shù)據(jù),只是提交用戶操作完畢后,到底要上傳哪些,通過提交鍵名或者鏈接,后臺來判斷最終用戶的選擇,整個思路也是如此
    $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">
    <h5>圖片</h5>
    <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> 。上傳后的照片默認會按照它們的EXIF日期來排序。</p>
    <div ng-repeat="item in thumb_default">
      <!-- 這里之所以寫個循環(huán),是為了后期萬一需要多個‘加號'框 -->
      <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">
    <h7 class="text-white">
      <strong>已上傳</strong>
    </h7>
  </div>
  <div ng-repeat="item in thumb" class="imgload">
  <!-- 采用angular循環(huán)的方式,對存入thumb的圖片進行展示 -->
    <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框架布局

以上是“Nodejs+angularjs結(jié)合multiparty如何實現(xiàn)多圖片上傳”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學(xué)習(xí)更多知識,歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI