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>  </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í)有所幫助,也希望大家多多支持腳本之家。
- angularjs實(shí)現(xiàn)多張圖片上傳并預(yù)覽功能
- angularjs客戶端實(shí)現(xiàn)壓縮圖片文件并上傳實(shí)例
- 通過AngularJS實(shí)現(xiàn)圖片上傳及縮略圖展示示例
- AngularJs上傳前預(yù)覽圖片的實(shí)例代碼
- angularjs點(diǎn)擊圖片放大實(shí)現(xiàn)上傳圖片預(yù)覽
- Angularjs上傳圖片實(shí)例詳解
- Angularjs實(shí)現(xiàn)上傳圖片預(yù)覽功能
- 詳解angularJS+Ionic移動端圖片上傳的解決辦法
- AngularJS實(shí)現(xiàn)圖片上傳和預(yù)覽功能的方法分析
相關(guān)文章
Node.js 實(shí)現(xiàn)搶票小工具 & 短信通知提醒功能
這篇文章主要介紹了Node.js 實(shí)現(xiàn)搶票小工具 & 短信通知提醒功能,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下2019-10-10koa-router路由參數(shù)和前端路由的結(jié)合詳解
這篇文章主要給大家介紹了關(guān)于koa-router路由參數(shù)和前端路由的結(jié)合的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用koa-router具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2019-05-05Node學(xué)習(xí)筆記:Node.js安裝及環(huán)境配置 史詩級詳細(xì)版【含測試與鏡像說明】
這篇文章主要介紹了Node學(xué)習(xí)筆記之Node.js安裝及環(huán)境配置方法,詳細(xì)分析了node.js的基本安裝、配置、環(huán)境變量設(shè)置、以及環(huán)境測試與鏡像使用說明,需要的朋友可以參考下2023-05-05Node.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