淘先锋技术网

首页 1 2 3 4 5 6 7

为项目添加上传头像功能,在线地址http://www.5rgame.com

一、前端代码

1.前端使用 FormData 方式上传文件,我直接使用ajax提交,其配置的参数主要有:

async: false,
cache: false,
credentials: true,  //跨域发送cookie,不跨域不用设置
contentType: false, //不可缺参数
processData: false, //不可缺参数

2.新建FormData,往里添加数据,如果使用from表单请看参考代码

var data = new FormData();
data.append('avatar', $(dom)[0].files[0]);
//name与value对应$(dom)[].files[]为上传的文件
data.append('token', token);//token为普通文字字段

3.参考代码

-------------html-----------------
<form id= "uploadForm">  
      <p >指定文件名: <input type="text" name="filename" value= ""/></p >  
      <p >上传文件: <input type="file" name="file"/></ p>  
      <input type="button" value="上传" onclick="doUpload()" />  
</form>  

-------------script-------------

function doUpload() {  
     var formData = new FormData($( "#uploadForm" )[]);  
     $.ajax({  
          url: '' ,  
          type: 'POST',  
          data: formData,  
          async: false,  
          cache: false,  
          contentType: false,  
          processData: false,  
          success: function (returndata) {  
              alert(returndata);  
          },  
          error: function (returndata) {  
              alert(returndata);  
          }  
     });  
}  

二,node服务器端代码

1.node文件上传要借助第三方模块,我使用的是multer,安装$ npm install --save multer
地址:https://github.com/expressjs/multer

2.借鉴别人的配置,建立一个multerUtil.js

var  multer=require('multer');
var storage = multer.diskStorage({
     //设置上传后文件路径,uploads文件夹会自动创建。
        destination: function (req, file, cb) {
            cb(null, './uploads')
       }, 
     //给上传文件重命名,获取添加后缀名
      filename: function (req, file, cb) {
          var fileFormat = (file.originalname).split(".");
          cb(null, file.fieldname + '-' + Date.now() + "." + fileFormat[fileFormat.length - ]);
      }
});  
//添加配置文件到muler对象。
var upload = multer({
    storage: storage,
    limits: { 
        fileSize:  *  * 
    }
});

//如需其他设置,请参考multer的limits,使用方法如下。
//var upload = multer({
//    storage: storage,
//    limits:{}
//});

 //导出对象
module.exports = upload;

3.接口文件代码,加上我图片裁剪功能,使用node-images模块,安装$ npm install images

const validator = require('validator');//表单验证
const muilter = require('../models/multerUtil.js');
const path = require('path');
const fs = require('fs');
const images = require("images"); //图片裁剪

//上传头像
    app.post('/upload', muilter.single('avatar'), function(req, res){
        //判断请求方式,获取token
        var token = req.body.token;
        var user = req.session.user;
        if(!token || user.token != token){
            return res.json({
                code: ,
                msg: 'Token错误'
            });
        }
        if(user.token != token){
            req.session.user = null;
        }
         // 没有附带文件
        if (!req.file) {
            return res.json({
                code: ,
                msg: '文件不存在'
            });
        }
        var extName = ''; //后缀名
        switch (req.file.mimetype) {
            case 'image/pjpeg':
                extName = 'jpg';
                break;
            case 'image/jpeg':
                extName = 'jpg';
                break;
            case 'image/png':
                extName = 'png';
                break;
            case 'image/x-png':
                extName = 'png';
                break;
        }
        if (extName.length === ) {
            return res.json({
                code: ,
                msg: '图片格式不正确'
            });
        }
        // 输出文件信息
//      console.log('====================================================');
//      console.log('fieldname: ' + req.file.fieldname);
//      console.log('originalname: ' + req.file.originalname);
//      console.log('encoding: ' + req.file.encoding);
//      console.log('mimetype: ' + req.file.mimetype);
//      console.log('size: ' + (req.file.size / ).toFixed() + 'KB');
//      console.log('destination: ' + req.file.destination);
//      console.log('filename: ' + req.file.filename);
//      console.log('path: ' + req.file.path);

        var createFolder = function(dirName){
            try{
                fs.accessSync(dirName, fs.F_OK);
            }catch(e){
                fs.mkdirSync(dirName);
            }
        };

        var uploadFolder = './uploads/avatar/';
        createFolder(uploadFolder)
        // 移动文件
        let oldPath = path.join(req.file.path);
        let newPath = path.join(uploadFolder, req.file.filename);
        let min = uploadFolder+'min-'+req.file.filename;
        images(oldPath).resize(, ).save(min);
        fs.rename(oldPath, newPath, (err) => {
            if (err) {
                console.log(err);
                return res.json({
                    code: ,
                    msg: '上传失败'
                });
            } else {
                //地址记得存入数据库
                return res.json({
                    code: ,
                    data: {
                        orihead: req.session.user.orihead,
                        head: req.session.user.head
                    },
                    msg: '上传成功'
                });
            }
        });
    })