压缩图片、微信小程序获取定位

322 阅读2分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第1天,点击查看活动详情 

有时候图片上传到服务器过大,这时候就需要我们前端可以将图片进行压缩后再上传至服务器

一、图片压缩

1、首先需要下载的包

npm i Compressor

2、导入下载的包

import Compressor from "Compressor";

3、具体代码实现

// 判断文件属于图片还是文件(压缩图片)
import Compressor from "compressorjs";
const beforeReadJudge = (file: any) => {
  let reg = new RegExp('^image/')
  if (reg.test(file.type)) {
      // 图片
      return new Promise((resolve, reject): void => {
          // 压缩图片
          new Compressor(file, {
              strict: false,
              maxWidth: 1024,
              maxHeight: 1024,
              convertTypes: ['image/png', 'image/webp', 'image/jpg'],
              resize: 'contain',
              convertSize: 10,
              quality: 0.6,
              success(res: any) {
                   console.log(res, 'compressorjs')
                  resolve(res)
              },
              error(err) {
                  console.log(err)
              }
          })
      })
  } else {
      // 非图片
      if (file.type === 'application/pdf') {
          return true
      } else {
          //this.$toast('只能上传图片及PDF文件!')
          return false
      }
  }
}
export default beforeReadJudge

4、直接函数调用即可

二、微信小程序定位

刚接触小程序,调用了小程序的获取定位方法,在使用前注意配置小程序的一些列配置

let signature = () => {
    let url_ticket = ''
    url_ticket = window.location.href.split('#')[0]
    getSignature({ url: encodeURIComponent(url_ticket) }).then((res: any) => {
        wx.config({
            beta: true,
            debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
            appId: appId, // 必填,公众号的唯一标识
            timestamp: res.result.timestamp, // 必填,生成签名的时间戳
            nonceStr: res.result.nonceStr, // 必填,生成签名的随机串
            signature: res.result.signature,// 必填,签名
            jsApiList: ['getLocation'] // 必填,需要使用的JS接口列表
        });
        wx.ready(() => {
            console.log('开始定位')
            wx.getLocation({
                type: 'wgs84', // 默认为wgs84的gps坐标,如果要返回直接给openLocation用的火星坐标,可传入'gcj02'
                success: (res: any) => {
                    console.log(res, '///坐标位置')
                },
                fail: (err: any) => {
                    console.log(err, 'faill')
                }
            })
        })
        wx.error((err: any) => {
            throw new Error(err)
        })
    })
}

以上就是我今天给大家分享的压缩图片与微信小程序的定位接口