vue+element-ui+axios实现图片上传
程序员文章站
2022-09-06 23:53:19
本文实例为大家分享了vue+element-ui+axios实现图片上传的具体代码,供大家参考,具体内容如下
&...
本文实例为大家分享了vue+element-ui+axios实现图片上传的具体代码,供大家参考,具体内容如下
<!doctype html> <html> <head> <meta charset="utf-8"> <meta http-equiv="x-ua-compatible" content="ie=edge,chrome=1"> <title>examples</title> <meta name="description" content=""> <meta name="keywords" content=""> <!-- 引入vue --> <script src="https://cdn.jsdelivr.net/npm/vue"></script> <!-- 引入axios --> <script src="https://unpkg.com/axios/dist/axios.min.js"></script> <!-- 引入样式 --> <link rel="stylesheet" href=https://unpkg.com/element-ui/lib/theme-chalk/index.css > <!-- 引入组件库 --> <script src="https://unpkg.com/element-ui/lib/index.js"></script> </head> <body> <div id="app"> <el-upload :action="posterurl" :before-upload="beforeupload" :http-request="(params)=>uploadimage(params)" :on-remove="(file, filelist)=>removeimage(file, filelist)" list-type="picture" accept="image/*" > <el-button size="small">选择图片</el-button> </el-upload> </div> <script type="text/javascript"> new vue({ el: '#app', data: { posterurl: '', imgurls: [], imgwidth: '320', imgheight: '400', }, methods: { beforeupload(file) { let _this = this; let _checksize = false; //是否需要指定上传图片的尺寸 if(file.size > 1024*500) { //大小超过500kb _this.$message.error('图片太大,请重新选择'); return false; } const issize = new promise((resolve, reject)=>{ let _url = window.url || window.webkiturl; let img = new image(); img.onload = function () { if(!_checksize || (_checksize && img.width==_this.imgwidth && img.height==_this.imgheight)) { resolve(); } else { reject(); } } img.src = _url.createobjecturl(file); }).then(()=>{ return file; }, ()=>{ _this.$message.error('图片尺寸不对,请重新选择'); return promise.reject(); }); return issize; }, uploadimage(params) { console.log(params); let uploaddata = new formdata(); uploaddata.append('file', params.file); let config = { headers: { 'content-type': 'multipart/form-data' } }; this.uploadposter('homed'+new date().gettime()+'/'+params.file.name, uploaddata, config) .then(res=>{ if(res.status == 200) { params.onsuccess(); this.imgurls.push({name:params.file.name, url:res.data.url}); console.log(this.imgurls); } }).catch(error=>{ params.onerror(); this.$message.error('上传失败'); }); }, removeimage(file, filelist) { console.log(filelist); }, uploadposter(url, obj, config) { let poster_upload_path = "http://xxxxxxxxxxxx/httpdocsup/poster/news/"; return axios.post(poster_upload_path+url, obj, config); } } }) </script> </body> </html>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
下一篇: .NET生成水印更好的方法实例代码