uniapp实现上传图片,并限制大小

uniapp实现上传图片,并限制大小

本文介绍使用官方api完成上传图片功能

html部分

<template><view class="carnew"><view class="flex"><view>车辆图片view><view v-if="carPicture" class="main"><image :src="carPicture" mode="aspectFill" @click.stop="lookPic({img:{urls:carPicture}})" class="main">image><u-icon name="close-circle-fill" size="44" color='#f00' @click="carPicture=null">u-icon>image>view><view v-else class="upload shadow" @click="uploadImg"><u-icon name="plus" size='28' color='#027AFF' >u-icon>view>view>view>
template>

js部分

<script>
export default {data() {return {carPicture:"",};},methods: {//查看大图lookPic(e) {let {img} = e,{urls,current} = img;if (Object.prototype.toString.call(urls) !== '[object Array]') {urls = [urls]current = 0}uni.previewImage({urls: urls,current: current,})},//上传图片uploadImg() {uni.chooseImage({count: 1,sizeType: ["original", "compressed"], //可以指定是原图还是压缩图,默认二者都有sourceType: ["album"], //从相册选择fileType: "image",success: (res) => {if(res.tempFiles[0].size>2*1024*100){uni.showToast({title:'图片大小超过2M,请重新选择照片',icon:'none'})		return}console.log(res, "选择图片完成");const tempFilePaths = res.tempFilePaths;uni.showLoading({title: "上传中",});uni.uploadFile({url: 后台url,filePath: tempFilePaths[0],//选中文件fileType: ".jpg,.jpeg,.png,.gif",//文件类型header: '根据需求添加header',name: "images",formData: {filename: "images",},success: (res) => {res = JSON.parse(res.data);if (res.code == 1) {// console.log(res, "上传成功");this.carPicture = res.data[0],uni.hideLoading();} else {uni.showToast({title: res.message,icon: "none",});}},complate: (res) => {console.log(res, "上传结束");},});},error: function (e) {console.log(e, "上传图片失败了");},});},},
};
</script>


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部