Uniapp 支持多种方式上传图片,以下是其中几种常用方式:
- 使用
uni.uploadFile()
上传图片,示例代码:
uni.chooseImage({ success: function (chooseImageRes) { uni.uploadFile({ url: 'http://example.com/upload', filePath: chooseImageRes.tempFilePaths[0], name: 'file', success: function (uploadFileRes) { console.log('upload success') }, fail: function (err) { console.log(err) } }) } })
- 使用
uni.getImageInfo()
获取图片信息,再使用uni.request()
上传图片,示例代码:
uni.chooseImage({ success: function (chooseImageRes) { uni.getImageInfo({ src: chooseImageRes.tempFilePaths[0], success: function (getImageInfoRes) { uni.request({ url: 'http://example.com/upload', method: 'POST', header: { 'content-type': 'multipart/form-data' }, formData: { file: chooseImageRes.tempFilePaths[0], width: getImageInfoRes.width, height: getImageInfoRes.height }, success: function (requestRes) { console.log('upload success') }, fail: function (err) { console.log(err) } }) } }) } })
- 使用第三方插件
uni-uploader
上传图片,示例代码:
<template> <view> <uploader :files="files" :options="options" @complete="onComplete"></uploader> </view> </template> <script> import Uploader from '@/components/uni-uploader/uni-uploader.vue' export default { components: { Uploader }, data () { return { files: [], options: { url: 'http://example.com/upload', method: 'POST', fileType: ['jpg', 'jpeg', 'png', 'gif'], fileName: 'file', formData: {}, header: {} } } }, methods: { onComplete ({type, index, file}) { if (type === 'add') { this.files.push(file) } else if (type === 'remove') { this.files.splice(index, 1) } else if (type === 'success') { console.log('upload success') } else if (type === 'fail') { console.log('upload fail') } } } } </script>
以上三种方式均可用于上传图片,具体选择哪种方式可以根据自己的需求和开发习惯进行选择。