美文网首页Node.js
nodejs移动端formidable上传图片-

nodejs移动端formidable上传图片-

作者: 疯子哦 | 来源:发表于2016-06-01 23:13 被阅读653次

    html代码:

    <form enctype='multipart/form-data' method="post" action='/file/uploading'>

    <input class="weui_uploader_input" id="upload" name="upload" type="file" accept="image/jpg,image/jpeg,image/png,image/gif">

    </form>

    <script>

    $('#upload').on('change',function(){

        $(this).closest('form').submit();

    });

    $('form').submit(function(){

    //  return false;

    });

    </script>

    服务端js

    var express=require('express');

    var router=express.Router();

    var formidable=require('formidable');

    var fs=require('fs');

    var gm=require('gm').subClass({imageMagick:true});

    router.post('/file/uploading',function(req,res,next){

    //res.header( 'Content-Type','text/javascript;charset=utf-8');        //设置返回字符串编码

    varform=newformidable.IncomingForm();//创建对象

    form.uploadDir=global.dirname+"/public/upload/source";//设置临时文件存放的路径

    form.encoding='utf-8';//设置上传数据的编码

    form.keepExtensions=true;//设置是否保持上传文件的拓展名

    form.maxFieldsSize=4*1024*1024;//文件大小

    form.parse(req,function(err, fields, files) {

    if(err) {

    res.render('/', {title: err });

    return;

    }

    var extName='jpg';//后缀名

    switch(files.upload.type) {

    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;

    case 'image/gif':

    extName='gif';

    break;

    }

    if(extName.length==0){

    res.send('上传文件类型有误!');

    return;

    }

    var avatarName=uuid.uuid(8,16)+'_normal'+'.'+extName;

    var newPath=form.uploadDir+"/"+avatarName;

    fs.renameSync(files.upload.path, newPath);  //重命名

    response.writeHead(200,{"Content-Type":"text.html"});

    response.write("received image:");

    response.end();

    });

    相关文章

      网友评论

        本文标题:nodejs移动端formidable上传图片-

        本文链接:https://www.haomeiwen.com/subject/ckohdttx.html