node中上传文件【base64文件流+插件调用】两种方式

xiaoxiao2021-02-28  144

--所需模块

安装模块  npm install 封装upload类 /** * 上传图片公共类 */ var os = require('os'); var formidable = require('formidable'), util = require('util'), fs = require('fs'); var request = require('request'); var path = require('path'); var config = require('../config'); var publicReq = require('./public'); var crypto = require('crypto'); var md5 = crypto.createHash('md5'); var date = new Date(); var year = date.getFullYear(); var month = date.getMonth() + 1; var day = date.getDate(); var adUrl = config.realUrl + 'public/uploads/ad'; var yearurl = config.realUrl + 'public/uploads/ad/' + year; var monthurl = config.realUrl + 'public/uploads/ad/' + year + '/' + month; var dayurl = config.realUrl + 'public/uploads/ad/' + year + '/' + month + '/' + day; var sizeOf = require('image-size'); //递归创建目录 同步方法 function mkdirsSync(dirname){ if(fs.existsSync(dirname)){ return true; }else{ if(mkdirsSync(path.dirname(dirname))){ fs.mkdirSync(dirname); return true; } } } exports.upload = function(req, res){ var accountId = req.session.scsInfor.accountInfo.accountId; mkdirsSync(dayurl); var dir = dayurl + '/'; var dirs = '/uploads/ad/' + year + '/' + month + '/' + day + '/'; var ms = Date.parse(date); var form = new formidable.IncomingForm(), files = [], fields = [], docs = [], filea = []; //存放目录 form.uploadDir = dir; form.on('field', function(field, value){ fields.push([field, value]); }).on('file', function(field, file){ var types = path.extname(file.name); if(typeof types[1] == 'undefined'){ var type = file.type.split('/')[1]; types += '.' + ( type == 'jpeg' ? 'jpg' : type ); } var num = Math.ceil(Math.random() * (10000 - 1) + 10); var content = (ms + num + accountId + file.name).toString(); var d = crypto.createHash('md5').update(content).digest('hex'); var fileName = dir + d + types; var fileNames = dirs + d + types; fs.renameSync(file.path, fileName); file.path = fileNames; docs.push(file); }).on('end', function(){ res.writeHead(200, { 'content-type' : 'text/plain' }); var imageSize = []; if(docs.length > 0){ docs.forEach(function(fv, fk){ imageSize.push(sizeOf('./public' + fv.path)); }); } var out = { Resopnse : { 'result-code' : 0, timeStamp : new Date(), files : docs, imageSize : imageSize } }; var sout = JSON.stringify(out); res.end(sout); }); form.parse(req, function(err, fields, files){ }); } //base64流方式保存图片 exports.baseUpload = function(req, res){ mkdirsSync(dayurl); var num = Math.ceil(Math.random() * (10000 - 1) + 10); var filePath = '/uploads/ad/' + year + '/' + month + '/' + day + '/' + Date.parse(date) + num + '.jpg'; var publicPath = config.realUrl + 'public' + filePath; var basefile = req.body.basefile; var base64 = basefile.replace(/^data:image\/\w+;base64,/, "");//去掉图片base64码前面部分data:image/png;base64 var dataBuffer = new Buffer(base64, 'base64'); //把base64码转成buffer对象, console.log('dataBuffer是否是Buffer对象:' + Buffer.isBuffer(dataBuffer)); fs.writeFile(publicPath, dataBuffer, function(err){//用fs写入文件 if(err){ return false; }else{ return res.json({ filePath : filePath }); } }) } //回调方式 exports.baseUploadCallback = function(basefile, callback){ mkdirsSync(dayurl); var num = Math.ceil(Math.random() * (10000 - 1) + 10); var filePath = '/uploads/ad/' + year + '/' + month + '/' + day + '/' + Date.parse(date) + num + '.jpg'; var publicPath = config.realUrl + 'public' + filePath; var base64 = basefile.replace(/^data:image\/\w+;base64,/, "");//去掉图片base64码前面部分data:image/png;base64 var dataBuffer = new Buffer(base64, 'base64'); //把base64码转成buffer对象, console.log('dataBuffer是否是Buffer对象:' + Buffer.isBuffer(dataBuffer)); fs.writeFile(publicPath, dataBuffer, function(err){//用fs写入文件 if(err){ return false; }else{ callback(filePath); } }) } 调用dome <% include ../common/header.html %> <body> <link rel="stylesheet" type="text/css" href="/stylesheets/v1/account/quaUpload.css"> <link rel="stylesheet" href="/stylesheets/v1/account_common.css"> <form action = "/demo/fileGo" class = "text" enctype="multipart/form-data"> <input type = "file" id = "file" name="file" style="display: none"> <div id="upload" picType='<%= qua %>' style = ""> <% if(filePath){ %> <img class="pic picfile" src='<%= filePath %>' picName='<%= filePath %>'/> <% }else{ %> <img src="/images/v1/images/icon_add.png" class="add picfile" picName=""> <% } %> </div> <p class="up_p">扫描件图片或正面拍照,保证信息清晰可见,大小不超过5M。</p> <div class='btn_cont'> </div> </form> <a href="javascript:void(0)" value="确定" class="submit" style="display:block">提交</a> <% include ../common/footer.html %> <script src="/javascripts/v1/lib/jquery/jquery.js"></script> <!-- <script src='/javascripts/v1/model/account/quaUpload.js'></script>--> </body> </html> <script> function getFileUrl(sourceId) { var url; if (navigator.userAgent.indexOf("MSIE") >= 1 && !(navigator.userAgent.indexOf("MSIE 10.0") > 0)) { // IE10取消了滤镜 url = document.selection.createRange().text; } else if (navigator.userAgent.indexOf("Firefox") > 0) { // Firefox url = window.URL.createObjectURL(document.getElementById(sourceId).files.item(0)); } else if (navigator.userAgent.indexOf("Chrome") > 0) { // Chrome url = window.URL.createObjectURL(document.getElementById(sourceId).files.item(0)); } else if (navigator.userAgent.indexOf("MSIE 10.0") > 0) { url = window.URL.createObjectURL(document.getElementById(sourceId).files.item(0)); } else { url = window.URL.createObjectURL(document.getElementById(sourceId).files.item(0)); } return url; } $('#upload').click(function(){ $('#file').click(); }); $("#file").change(function() { var url = getFileUrl('file'); getBase64(url).then(function(base64){ $.ajax({ type: 'POST', url: '/upload/baseUpload', data: { basefile : base64 }, success: function (res) { if(res.filePath){ $('.picfile').removeClass('add').addClass('pic').addClass('up'); $(".picfile").attr("src", base64); $('.picfile').attr('picName',res.filePath); }else{ alert('上传失败请重新选择一次图片'); } } }) },function(err){ console.log(err); }); }); $('.submit').click(function(){ if($('.picfile').hasClass('up')){ $.ajax({ type: 'POST', url: '/account/fileUp', data: { qua : $('#upload').attr('picType'), fileName : $('.picfile').attr('picName') }, success: function (res) { if (res.code == 0) { window.location.href = '/account/qualifications'; } else { alert(res.reason); } } }) }else{ if($('.picfile').hasClass('pic')){ window.location.href = '/account/qualifications'; }else{ alert('请选择图片'); } } }) //转换base64 function getBase64(img){//传入图片路径,返回base64 function getBase64Image(img,width,height) {//width、height调用时传入具体像素值,控制大小 ,不传则默认图像大小 var canvas = document.createElement("canvas"); canvas.width = width ? width : img.width; canvas.height = height ? height : img.height; var ctx = canvas.getContext("2d"); ctx.drawImage(img, 0, 0, canvas.width, canvas.height); var dataURL = canvas.toDataURL(); return dataURL; } var image = new Image(); image.src = img; var deferred=$.Deferred(); if(img){ image.onload =function (){ deferred.resolve(getBase64Image(image));//将base64传给done上传处理 } return deferred.promise();//问题要让onload完成后再return sessionStorage['imgTest'] } } </script>
转载请注明原文地址: https://www.6miu.com/read-18250.html

最新回复(0)