Home >Web Front-end >uni-app >How to implement image upload and preview in uniapp
How to implement image upload and preview in uniapp
In modern social networks and e-commerce applications, image upload and preview functions are very common requirements. This article will introduce how to implement the image upload and preview functions in uniapp, and give specific code examples.
1. Implementation of the image upload function
<template> <view> <image v-for="(item, index) in images" :key="index" :src="item.url"></image> <button @tap="chooseImage">选择图片</button> <button @tap="uploadImage">上传图片</button> </view> </template> <script> export default { data() { return { images: [], // 用于存储选择的图片 } }, methods: { chooseImage() { uni.chooseImage({ count: 9, // 最多选择9张图片 success: (res) => { this.images = this.images.concat(res.tempFilePaths) } }) }, uploadImage() { this.images.forEach((item, index) => { uni.uploadFile({ url: 'http://example.com/upload', // 上传图片的接口地址 filePath: item, name: 'file', success: (res) => { console.log(res.data) // 上传成功后的返回数据 } }) }) } } } </script>
2. Implementation of the image preview function
<template> <view> <image v-for="(item, index) in images" :key="index" :src="item.url" @tap="previewImage(index)"></image> <button @tap="chooseImage">选择图片</button> <button @tap="uploadImage">上传图片</button> </view> </template> <script> export default { data() { return { images: [], // 用于存储选择的图片 } }, methods: { chooseImage() { uni.chooseImage({ count: 9, // 最多选择9张图片 success: (res) => { const tempImages = res.tempFilePaths.map((item) => { return { url: item } }) this.images = this.images.concat(tempImages) } }) }, uploadImage() { // 省略上传图片的代码 }, previewImage(index) { const urls = this.images.map((item) => { return item.url }) uni.previewImage({ urls: urls, current: index // 当前预览的图片索引 }) } } } </script>
Through the above operations, the image upload and preview functions are implemented in uniapp. The user can click the Select Picture button to select the picture to be uploaded, and then click the Upload Picture button to upload the picture to the server. The pictures on the page can be clicked to preview, and users can slide to browse and zoom in and out of the pictures on the preview interface. When developing uniapp applications, we can customize the style and functions according to actual needs to adapt to different application scenarios.
The above is the detailed content of How to implement image upload and preview in uniapp. For more information, please follow other related articles on the PHP Chinese website!