• nodejs实现本地上传图片并预览功能(express4.0+)


    Express为:4.13.1  multyparty: 4.1.2

    代码主要实现本地图片上传到nodejs服务器的文件下,通过取图片路径进行图片预览

    写在前面:计划实现图片上传预览功能,但是本地图片上传所获得路径为 C:fakepath"+文件名的形式,得不到文件真实路径,所以无法直接预览,于是采用将图片上传至服务器,传回服务器路径,实现预览。前端采用通过ajax方式上传文件,使用FormData进行ajax请求  ,nodejs端采用multiparty模块

    相关查看文档:

    通过Ajax方式上传文件,使用FormData进行Ajax请求

    node-multiparty github

    FormData - Web APIs | MDN

    部分代码:

    <form name='picForm' action = "javascript:;"method="post" encype = "multipart/form-data" >
        <input type="file" id="test" id="j_imgfile">
    </form>
    <div>
        <img src="" id="j_imgPic">
    </div>
    html

    js中采用change事件,即当选完图片时就发送ajax请求

        $('#j_imgfile').on('change',function(){
            // 判断上传文件类型
            var objFile = $('#j_imgfile').val();
            var objType = objFile.substring(objFile.lastIndexOf(".")).toLowerCase();
            var formData = new FormData(document.forms.namedItem("picForm"));
            console.log(objType);
            if(!(objType == '.jpg'||objType == '.png'))
            {
                alert("请上传jpg、png类型图片");
                return false;
            }else{
                $.ajax({
                    type : 'post',
                    url : '/uploadUserImgPre',
                    data: formData ,
                    processData:false,
                    async:false,
                    cache: false,  
                      contentType: false, 
                    success:function(re){
                        re.imgSrc = re.imgSrc.replace('public','');
                        re.imgSrc = re.imgSrc.replace(/\/g,'/');
                        $('#j_imgPic').attr('src',re.imgSrc);
                    },
                    error:function(re){
                        console.log(re);
                    }
                });    
            }
        });
    js

     nodejs app.js里代码

    app.post('/uploadUserImgPre',routes.users.uploadUserImgPre);

    routes/users.js 里代码

    exports.uploadUserImgPre = function(req, res, next) {
      //生成multiparty对象,并配置上传目标路径
      var form = new multiparty.Form({uploadDir: './public/files/images'});
      form.parse(req, function(err, fields, files) {
        var filesTmp = JSON.stringify(files);
     
        if(err){
          console.log('parse error: ' + err);
        } else {
          testJson = eval("(" + filesTmp+ ")"); 
          console.log(testJson.fileField[0].path);
          res.json({imgSrc:testJson.fileField[0].path})
          console.log('rename ok');
        }
      });
    }
    users.js

    部分说明:

    文件上传至服务器后 路径path变为:publicfilesimagesW-jy9YsxsPjNpQHslzGvdXBk.jpg

    由于在app.js中设置过public为默认路径,所以整理地址时需要去掉public,并且把‘’变成‘/’

    app.use(express.static(path.join(__dirname, 'public')));

     最后效果大概是这样的,html部分不一样~我的是jade模板,还有css什么的,并木有列出来

    点击空白处,上传图片,接下来的功能就是点击上传把地址放到数据库里~(这个功能还木有做呢)

     

  • 相关阅读:
    Android
    列出控制原理来解决
    【ORACLE】spfile失落的处理
    Cocos2d-x 脚本语言Lua基本语法
    远东转载这说明一些有实力的话人工智能协会的思维和潜意识之间移动的一篇文章
    日志框架的实时变化,即日起,思维详细框架(4)
    [Python] Scatter Plot for daily return
    [Python] Use a Python Generator to Crawl the Star Wars API
    [Poi] Setup PostCSS and Tailwind with Poi
    [Poi] Build and Analyze Your JavaScript Bundles with Poi
  • 原文地址:https://www.cnblogs.com/a67cm/p/5217462.html
Copyright © 2020-2023  润新知