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>
服務(wù)端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');? ? ? ? //設(shè)置返回字符串編碼
varform=newformidable.IncomingForm();//創(chuàng)建對象
form.uploadDir=global.dirname+"/public/upload/source";//設(shè)置臨時文件存放的路徑
form.encoding='utf-8';//設(shè)置上傳數(shù)據(jù)的編碼
form.keepExtensions=true;//設(shè)置是否保持上傳文件的拓展名
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();
});