亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

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

 更新時間:2017年09月29日 09:51:49   作者:愛前端的小白  
這篇文章主要介紹了Nodejs+angularjs結(jié)合multiparty實(shí)現(xiàn)多圖片上傳的示例代碼,具有一定的參考價值,感興趣的小伙伴們可以參考一下

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

此前也在網(wǎng)站看了很多篇文章,有關(guān)的內(nèi)容說多不多,說少也不少,但我一一試過以后有成功的,也有沒有成功的,折磨了我很長時間,最終也是成功實(shí)現(xiàn)了,于是想寫下這篇文章,分享我的代碼,也希望后人不要踏進(jì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)自己的項(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; /*以上傳的時間戳命名*/
  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)建一個FileReader接口
  $scope.form = {   //用于綁定提交內(nèi)容,圖片或其他數(shù)據(jù)
    image:{},
  };
  $scope.thumb = {};   //用于存放圖片的base64
  $scope.thumb_default = {  //用于循環(huán)默認(rèn)的‘加號'添加圖片的框
    1111:{}
  };

  $scope.img_upload = function(files) {    //單次提交圖片的函數(shù)
    $scope.guid = (new Date()).valueOf();  //通過時間戳創(chuàng)建一個隨機(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();   //以下為像后臺提交圖片數(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">
    <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)會按照它們的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">
    <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í)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • Node.js 實(shí)現(xiàn)搶票小工具 & 短信通知提醒功能

    Node.js 實(shí)現(xiàn)搶票小工具 & 短信通知提醒功能

    這篇文章主要介紹了Node.js 實(shí)現(xiàn)搶票小工具 & 短信通知提醒功能,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下
    2019-10-10
  • 將node安裝到其他盤的超詳細(xì)步驟與說明

    將node安裝到其他盤的超詳細(xì)步驟與說明

    基本現(xiàn)在很多主流的前端框架都用了node.js 但是node裝起來確實(shí)頭疼,下面這篇文章主要給大家介紹了關(guān)于如何將node安裝到其他盤的超詳細(xì)步驟與說明,需要的朋友可以參考下
    2023-06-06
  • koa-router路由參數(shù)和前端路由的結(jié)合詳解

    koa-router路由參數(shù)和前端路由的結(jié)合詳解

    這篇文章主要給大家介紹了關(guān)于koa-router路由參數(shù)和前端路由的結(jié)合的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用koa-router具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-05-05
  • Node學(xué)習(xí)筆記:Node.js安裝及環(huán)境配置 史詩級詳細(xì)版【含測試與鏡像說明】

    Node學(xué)習(xí)筆記:Node.js安裝及環(huán)境配置 史詩級詳細(xì)版【含測試與鏡像說明】

    這篇文章主要介紹了Node學(xué)習(xí)筆記之Node.js安裝及環(huán)境配置方法,詳細(xì)分析了node.js的基本安裝、配置、環(huán)境變量設(shè)置、以及環(huán)境測試與鏡像使用說明,需要的朋友可以參考下
    2023-05-05
  • NodeJs模擬登陸正方教務(wù)

    NodeJs模擬登陸正方教務(wù)

    網(wǎng)上已經(jīng)有很多關(guān)于模擬登陸正方教務(wù)的作品了,基于 PHP,Python,Java,.Net 加上NodeJs,這幾門語言都可以實(shí)現(xiàn)模擬登陸,模擬登陸的技術(shù)點(diǎn)不是特別難,這里記錄一下利用Node碰到的一些坑,以及一些解決思路。
    2017-04-04
  • node版本過高該如何將node版本降低

    node版本過高該如何將node版本降低

    我們常使用nvm來管理node.js的版本,這樣就可以根據(jù)自己的需要來回切換node.js版本,下面這篇文章主要給大家介紹了關(guān)于node版本過高該如何將node版本降低的相關(guān)資料,需要的朋友可以參考下
    2023-01-01
  • Node.js實(shí)現(xiàn)mysql連接池使用事務(wù)自動回收連接的方法示例

    Node.js實(shí)現(xiàn)mysql連接池使用事務(wù)自動回收連接的方法示例

    這篇文章主要介紹了Node.js實(shí)現(xiàn)mysql連接池使用事務(wù)自動回收連接的方法,結(jié)合實(shí)例形式分析了node.js操作mysql連接池實(shí)現(xiàn)基于事務(wù)的連接回收操作相關(guān)技巧,需要的朋友可以參考下
    2018-02-02
  • 利用Node.js檢測端口是否被占用的方法

    利用Node.js檢測端口是否被占用的方法

    這篇文章主要給大家介紹了關(guān)于利用Node.js檢測端口是否被占用的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。
    2017-12-12
  • 基于Node.js構(gòu)建一個靈活的CLI命令行工具

    基于Node.js構(gòu)建一個靈活的CLI命令行工具

    在軟件開發(fā)中,命令行界面(CLI)工具是必不可少的助手,本文主要介紹了如何使用Node.js構(gòu)建一個靈活的CLI工具,涵蓋從基礎(chǔ)命令處理到復(fù)雜的交互式問答和遠(yuǎn)程模板下載,需要的可以參考下
    2024-03-03
  • nodeJs項(xiàng)目在阿里云的簡單部署

    nodeJs項(xiàng)目在阿里云的簡單部署

    這篇文章主要為大家詳細(xì)介紹了nodeJs項(xiàng)目在阿里云的簡單部署,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2020-11-11

最新評論