欢迎体验个人小程序
表情小作坊 轻松定制表情包 三连图 文字转图片
吃什么都行 解决广大用户吃饭选择恐惧症的问题
选择图片及文件上传下载及保存文件
- 操作1:选择图片并上传
- 操作2:下载文件并保存
wxml
<button bindtap='chooseAndUpload'>选择图片并上传</button>
<button bindtap='download'>下载图片并保存</button>
<image class='image' src='{{imageUrl}}'></image>
wxss
.image {
width: 300rpx;
height: 300rpx;
}
.js
Page({
/**
* 页面的初始数据
*/
data: {
imageUrl: "",
},
//选择图片并上传
chooseAndUpload: function () {
var that = this
wx.chooseImage({
success: function (res) {
console.log(res)
//返回的结果是选择的图片数组
//文件的临时路径,在小程序本次启动期间可以正常使用,如需持久保存,需在主动调用 wx.saveFile,在小程序下次启动时才能访问得到
var tempFilepath = res.tempFilePaths[0]
//上传文件
wx.uploadFile({
url: 'http://localhost:8080/add_file', //接口地址
//指定文件路径
filePath: tempFilepath,
name: 'file',
success: function (res) {
console.log(res)
}
})
},
})
},
//下载图片
download: function () {
var that = this
wx.downloadFile({
url: 'http://localhost:8080/123.jpg',
//文件下载成功
success: function (res) {
// 只要服务器有响应数据,就会把响应内容写入文件并进入 success 回调,业务需要自行判断是否下载到了想要的内容
if (res.statusCode === 200) {
console.log(res)
//文件的临时路径,在小程序本次启动期间可以正常使用,如需持久保存,需在主动调用 wx.saveFile,在小程序下次启动时才能访问得到
var pic = res.tempFilePath
//保存图片到本地
wx.saveFile({
tempFilePath: pic,
success: function (res) {
console.log(res)
//文件的本地路径
var localPath = res.savedFilePath
that.setData({
imageUrl: localPath
})
}
})
}
}
})
}
})
api的调用已经在注释里了
点击下载图片并保存
demo中的接口地址为我自己的项目,若需要请点击蛋哥
注意:
- 选择图片成功后返回的是一个数组tempFilePaths(选择可有多张图片)
- 选择和上传成功返回的tempFilePath是临时文件,在小程序本次启动期间可以正常使用,如需持久保存,需再主动调用wx.saveFile,才能在小程序下次启动时访问得到
获取当前位置并在地图上显示
获取当前位置
wxml里只有一个textview显示定位信息locationMsg
.js
Page({
/**
* 页面的初始数据
*/
data: {
locationMsg: "当前位置:"
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
var that = this
//获取位置后打开地图查看当前位置
wx.getLocation({
success: function (res) {
console.log(res)
that.setData({
locationMsg: that.data.locationMsg + "\nlatitude:" + res.latitude + "\nlongitude:" + res.longitude
})
},
})
}
})
结果:
已经获取到当前位置了,获取位置时可以指定获取的坐标系,返回的结果也有其它的参数可以去API查阅
查看当前位置
可以在获取当前位置的回调里加上代码
//查看位置
wx.openLocation({
latitude: res.latitude,
longitude: res.longitude,
scale: 10,
name: '西港新界',
address: "浙江省杭州市西湖区",
})
结果:
需要注意:
wx.chooseLocation(OBJECT)和wx.openLocation(OBJECT)需要用户授权 scope.userLocation
申请用户授权的方法稍后补充