以下是一个将标题和图片上传到后端 PHP 的微信小程序示例,包括 WXML、WXSS 和 JS 代码:
WXML 代码:
<view class="container">
<form bindsubmit="formSubmit">
<view class="input-group">
<input type="text" name="title" placeholder="请输入标题" bindinput="onTitleInput" value="{{title}}" />
</view>
<view class="input-group">
<image src="{{imageUrl}}" mode="aspectFit" bindtap="chooseImage" />
</view>
<button type="submit">提交</button>
</form>
</view>
在这个示例中,我们使用一个表单来上传标题和图片。表单包含一个文本输入框和一个图片预览区域。当用户在输入框中输入标题时,我们使用 bindinput 将输入框的值绑定到 title 变量上。当用户选择图片时,我们使用 bindtap 调用 chooseImage 方法来选择图片并将其预览在页面上。当用户点击提交按钮时,我们将调用 formSubmit 方法来上传标题和图片。
WXSS 代码:
.container {
display: flex;
flex-direction: column;
align-items: center;
padding: 20rpx;
}
.input-group {
margin-bottom: 20rpx;
}
input {
width: 100%;
border: 1rpx solid #ccc;
border-radius: 4rpx;
padding: 10rpx;
font-size: 28rpx;
box-sizing: border-box;
}
image {
width: 100%;
height: 200rpx;
object-fit: cover;
border: 1rpx solid #ccc;
border-radius: 4rpx;
}
在这个示例中,我们使用了一些基本的样式来定义页面的布局和样式。这些样式可以根据您的具体需求进行调整。
JS 代码:
Page({
data: {
title: '',
imageUrl: ''
},
onTitleInput: function(event) {
this.setData({
title: event.detail.value
});
},
chooseImage: function() {
var self = this;
wx.chooseImage({
count: 1,
success: function(res) {
var tempFilePaths = res.tempFilePaths;
self.setData({
imageUrl: tempFilePaths[0]
});
}
});
},
formSubmit: function(event) {
var self = this;
wx.uploadFile({
url: 'https://example.com/upload.php',
filePath: self.data.imageUrl,
name: 'file',
formData: {
'title': self.data.title
},
success: function(res) {
wx.showToast({
title: '上传成功',
icon: 'success',
duration: 2000
});
}
});
}
});
在这个示例中,我们定义了一个 Page 对象,其中包含了用于上传标题和图片的方法。当用户在输入框中输入标题时,我们使用 onTitleInput 方法将输入框的值绑定到 title 变量上。当用户选择图片时,我们使用 chooseImage 方法来选择图片并将其预览。