返回

上传图片

发布时间:2022-09-18 10:54:10 356
# javascript# webkit# java# 数据库# 数据

<template>
<div id="infocenter">
<!-- 头部标题栏 -->
<HeadTop title="个人信息中心">
<span slot="left">
<div @click="routerback">
<Icon type="md-arrow-round-back" size="20" /><span>返回</span>
</div>
</span>
<span slot="right"></span>
</HeadTop>

<!-- 内容 -->
<div>
<div class="upload">
<!-- 个人信息 -->
<div style="width:280px;margin:0 auto;text-align:center;">
<!-- 展示用户信息,可以修改 -->
<div v-if="showInfo">
<Form :model="info" label-position="right" :label-width="100">
<img :src="this.info.avatarurl" width="60" height="60"/>
<FormItem label="昵称:" style="text-align:left;">
{{this.info.username}}
</FormItem>
<FormItem label="简介:" style="text-align:left;">
{{this.info.disc}}
</FormItem>
</Form>
<Button type="warning" @click="changeInfo" ghost>修改</Button>
</div>

<!-- 修改用户信息表单 -->
<div v-if="showForm">
<Form :model="info" label-position="left" :label-width="100">

<FormItem label="昵称">
<Input v-model="info.username"></Input>
</FormItem>
<FormItem label="简介">
<Input type="textarea" v-model="info.disc" :autosize="{minRows: 2,maxRows: 5}" ></Input>
</FormItem>
</Form>
<Button type="success" @click="sureInfo" ghost>确定</Button>
<Button type="info" @click="cancelInfo" ghost>取消</Button>
</div>
{{this.info}}
{{this.oldinfo}}


</div>
<!-- 上传图片 -->
<div v-if="false">
<!--图片上传-->
<div class="weui-gallery" id="gallery">
<span class="weui-gallery__img" id="galleryImg"></span>
<div class="weui-gallery__opr">
<a href="javascript:" class="weui-gallery__del">
<i class="weui-icon-delete weui-icon_gallery-delete"></i>
</a>
</div>
</div>
<div class="weui-cells weui-cells_form">
<div class="weui-cell">
<div class="weui-cell__bd">
<textarea class="weui-textarea" v-model="content" placeholder="你想说啥" rows="3"></textarea>
</div>
</div>
<div class="weui-cell">
<div class="weui-cell__bd">
<div class="weui-uploader">
<div class="weui-uploader__bd">
<ul class="weui-uploader__files" id="uploaderFiles">
<li ref="files" class="weui-uploader__file" v-for="(image,index) in images" :key="index"
:style="'backgroundImage:url(' + image +' )'"><span @click="deleteimg(index)" class="x">×</span></li>
</ul>
<div v-show="images.length < maxCount" class="weui-uploader__input-box">
<input @change="change" id="uploaderInput" class="weui-uploader__input " type="file"
multiple accept="image/*">
</div>
</div>
</div>
</div>
</div>
</div>
<a class="weui-btn weui-btn_primary btn-put" style="margin: 20px " @click.prevent.once="put">发送</a>
</div>
</div>
</div>

</div>
</template>

<script>
import store from '../../vuex/store'
import HeadTop from '../components/HeadTop/HeadTop'
import axios from 'axios'

export default {
name:"Infocenter",
data(){
return {
//用户框,修改框 展示与否
showInfo:true,
showForm:false,
//用户信息(来接受路由传递过来的query)
info:{},
//缓存用户信息,防止取消修改信息后原信息丢失
oldinfo:{},


//iview 表单默认配置
formLeft: {
input1: '',
input2: '',
input3: ''
},
//上传头像相关
content: '',//分享动态的文字内容
maxSize: 10240000 / 2,//图片的最大大小
maxCount: 8,//最大数量
filesArr: [],//保存要上传图片的数组
images: []//转成base64后的图片的数组
}
},
//引入vuex
store,
//引入子组件
components: {
HeadTop,
},
//方法
methods:{
//后退:返回上一个页面
routerback(){
this.$router.back(-1);
},
changeInfo(){
// 用户信息框消失,修改信息框展示
this.showInfo = false;
this.showForm = true;

},
sureInfo(){
// 用户信息框展示,修改信息框消息
this.showInfo = true;
this.showForm = false;
},
cancelInfo(){
// 用户信息框展示,修改信息框消息
this.showInfo = true;
this.showForm = false;
//缓存用户信息,防止取消修改信息后原信息丢失
this.info = this.oldinfo;

},

// 上传头像相关的所有方法--开始
//删除图片
deleteimg(index) {
this.filesArr.splice(index, 1);
this.images.splice(index, 1);
},
//改变图片
change(e) {
let files = e.target.files;
// 如果没有选中文件,直接返回
if (files.length === 0) {
return;
}
if (this.images.length + files.length > this.maxCount) {
Toast('最多只能上传' + this.maxCount + '张图片!');
return;
}
let reader;
let file;
let images = this.images;
for (let i = 0; i < files.length; i++) {
file = files[i];
this.filesArr.push(file);
reader = new FileReader();
if (file.size > self.maxSize) {
Toast('图片太大,不允许上传!');
continue;
}
reader.onload = (e) => {
let img = new Image();
img.onload = function () {
let canvas = document.createElement('canvas');
let ctx = canvas.getContext('2d');
let w = img.width;
let h = img.height;
// 设置 canvas 的宽度和高度
canvas.width = w;
canvas.height = h;
ctx.drawImage(img, 0, 0, w, h);
let base64 = canvas.toDataURL('image/png');
images.push(base64);
};
img.src = e.target.result;
};
reader.readAsDataURL(file);
}
},
//发送方法
put() {
let self = this;
let content = this.content;
let param = new FormData();
param.append('content', content);
param.append('username', 'wofsfsdf');
this.filesArr.forEach((file) => {
param.append('file2', file);
});
axios.post('http://localhost:4444/uploadFile', param, {
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}
}).then(function (result) {
console.log(result.data);
this.$router.push({path: '/world'});
Toast(result.data.msg)
})
},// 上传头像相关的所有方法--结束


},//methods-end
//beforeCreate 将路由中的 用户信息 赋值到 data(){} 中
beforeCreate(){
//防止token已经过期
var localtoken = localStorage.getItem("token");
var localusername = localStorage.getItem("user_name");
var localparams = {
token:localtoken,
user_name:localusername
};
this.$axios({
url:"http://localhost:4444/users/islogin",
method:"get",
params:localparams
})
.then(res=>{
console.log('这里是vue初始化生命周期:');
if(res.data.status == 200){
this.info = res.data.info;
//对象赋值,分配一块新的内存空间
this.oldinfo = Object.assign({}, res.data.info);
console.log(res.data.info);
}
})
.catch(err=>{
console.log(err)
})
},//beforreCreate-end

}
</script>

<style scoped>


</style>

 

var express = require('express');
var router = express.Router();
var path = require("path");
var User = require("../models/User");
var Info = require("../models/Info");


//图片上传模块
var multer = require('multer');

let OSS = require('ali-oss');
//阿里云oss配置自己去官网瞧
let client = new OSS({
region: 'oss-cn-shanghai',
accessKeyId: '****',
accessKeySecret: '******'
});
client.useBucket('******');

/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});

async function put(fileName, filePath, cb) {
try {
let result = await client.put(fileName, filePath);
fs.unlinkSync("public/images/uploads/" + result.name);
cb(result)
} catch (err) {
console.log(err);
}
}

let filePath;
let fileName;

let Storage = multer.diskStorage({
destination: function (req, file, cb) {//计算图片存放地址
cb(null, './public/images/uploads');
},
filename: function (req, file, cb) {//图片文件名
fileName = Date.now() + '_' + parseInt(Math.random() * 1000000) + '.png';
filePath = '/public/images/uploads/' + fileName;
cb(null, fileName)
}
});
let upload = multer({ storage: Storage }).any();//file2表示图片上传文件的key

router.post('/uploadFile', function (req, res, next) {
upload(req, res, function (err) {
let content = req.body.content || '';
let username = req.body.username;
let imgs = [];//要保存到数据库的图片地址数组
if (err) {
return res.end(err);
}
if (req.files.length === 0) {
new Pyq({
writer: username,
content: content
}).save().then((result) => {
res.json({
result: result,
code: '0',
msg: '上传成功'
});
})
}
/*client.delete('public/img/1.png', function (err) {
console.log(err)
});*/
let i = 0;
req.files.forEach((item, index) => {
let filePath = `./public/images/uploads/${item.filename}`;
put(item.filename, filePath, (result) => {
imgs.push(result.url);
i++;
if (i === req.files.length) {
//forEach循环是同步的,但上传图片是异步的,所以用一个i去标记图片是否全部上传成功
//这时才把数据保存到数据库
new Pyq({
content: content,
writer: username,
pimg: imgs
}).save().then(() => {
res.json({
code: '0',
msg: '发布成功'
});
})
}
})
})
})
});


module.exports = router;

特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报
评论区(0)
按点赞数排序
用户头像
精选文章
thumb 中国研究员首次曝光美国国安局顶级后门—“方程式组织”
thumb 俄乌线上战争,网络攻击弥漫着数字硝烟
thumb 从网络安全角度了解俄罗斯入侵乌克兰的相关事件时间线
下一篇
OSS 2022-09-18 10:18:23