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>
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐