本文服务端主要为nodejs,利用multer中间件完成图片上传功能。服务端安装express框架和multer。
npm install express --save
npm install multer --save
服务端启动文件代码:
var express = require('express');
var app = express();
var fileRouter = require('./src/router/fileupload.js')
var bodyParser = require('body-parser');
app.use(express.static('dist'))
app.use(express.static('dist2'))
app.use(bodyParser.json())
app.use('/upload/', fileRouter);
app.get('/', function(req, res) {
res.redirect('dist/index.html')
});
var server = app.listen(5050, function() {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
处理图片上传路由:
var express = require('express');
var router = express.Router();
var fs = require('fs');
var multer = require('multer');
var Storage = multer.diskStorage({
destination: function (req, file, cb) {//计算图片存放地址
cb(null, './imgs')
},
filename: function (req, file, cb) {//图片文件名
console.log(file);
cb(null, file.originalname)
}
})
var upload = multer({storage:Storage}).single('file2');//file2表示图片上传文件的key
router.post('/uploadFile',function(req, res, next){
upload(req, res, function (err) {
console.log(err)
if (err) {
return res.end(err);
}
return res.end("File uploaded sucessfully!.");
});
})
module.exports = router;
至此我们便完成了服务端图片上传的代码。
客户端上传组件主要借助weui的样式,感谢前辈写好的样式哈哈。
代码如下:部分代码可能无用,请自动忽略哈。
<template>
<div>
<div class="weui-cells weui-cells_form" id="uploaderCustom">
<div class="weui-cell">
<div class="weui-cell__bd">
<div class="weui-uploader">
<div class="weui-uploader__hd">
<p class="weui-uploader__title">图片上传p>
div>
<div class="weui-uploader__bd">
<ul class="weui-uploader__files" id="uploaderCustomFiles">ul>
<div class="weui-uploader__input-box">
<input id="uploaderCustomInput" class="weui-uploader__input js_file" type="file">
div>
div>
div>
div>
div>
div>
<x-button type="primary" class='w80 mt3' action-type='button' @click.native='upload()'>上传x-button>
div>
template>
<script>
import {
Toast,
XButton,
Group,
Cell
} from 'vux'
export default {
components: {
XButton,
Group,
Cell
},
data() {
return {
// note: changing this line won't causes changes
// with hot-reload because the reloaded component
// preserves its current state and we are modifying
// its initial state.
msg: 'Hello World!',
maxSize: 10240000,
maxCount: 5,
filesArr: []
}
},
methods: {
bindEvent() {
let self = this;
$("#uploaderCustomInput").on('change', function(event) {
let files = event.target.files;
// 如果没有选中文件,直接返回
if (files.length === 0) {
return;
}
for (var i = 0; i < files.length; i++) {
let file = files[i];
self.filesArr.push(file)
let reader = new FileReader();
if (file.size > self.maxSize) {
self.$alert('图片太大,不允许上传!');
continue;
}
if ($('.weui_uploader_file').length >= self.maxCount) {
self.$alert(`最多只能上传 ${maxCount} 张图片!`);
return;
}
reader.onload = function(e) {
var img = new Image();
img.onload = function() {
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
var w = img.width;
var h = img.height;
// 设置 canvas 的宽度和高度
canvas.width = w;
canvas.height = h;
ctx.drawImage(img, 0, 0, w, h);
var base64 = canvas.toDataURL('image/png');
// 插入到预览区
var $preview = $('')"> ');
$('#uploaderCustomFiles').append($preview);
}
img.src = e.target.result;
}
reader.readAsDataURL(file);
}
})
},
upload() {
let self = this;
this.filesArr.map((file) => {
let param = new FormData();
param.append('file2', file);
self.$http.post('/upload/uploadFile', param, {
'Content-Type': 'multipart/form-data;'
}).then(function(result) {
console.log(result)
})
})
}
},
mounted() {
this.bindEvent();
}
}
script>
<style>
.vux-demo {
text-align: center;
}
.logo {
width: 100px;
height: 100px
}
.weui-uploader__bd {
margin-bottom: -4px;
margin-right: -9px;
overflow: hidden;
}
.weui-uploader__input-box {
float: left;
position: relative;
margin-right: 9px;
margin-bottom: 9px;
width: 77px;
height: 77px;
border: 1px solid #d9d9d9;
}
.weui_uploader_file {
float: left;
margin-right: 9px;
margin-bottom: 9px;
width: 79px;
height: 79px;
background: no-repeat center center;
background-size: cover;
list-style: none;
}
.weui-uploader__input {
position: absolute;
z-index: 1;
top: 0;
left: 0;
width: 100%;
height: 100%;
opacity: 0;
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
}
.weui-uploader__input-box:before {
width: 2px;
height: 39.5px;
}
.weui-uploader__input-box:after {
width: 39.5px;
height: 2px;
}
.weui-uploader__input-box:after,
.weui-uploader__input-box:before {
content: " ";
position: absolute;
top: 50%;
left: 50%;
-webkit-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
background-color: #d9d9d9;
}
style>