小程序上传文件到服务器并回显可删除,包含图片视频文档等格式,附源码!
我这里应用了vant-weapp插件,其实原理都是一样的,主要是调用微信的wx.uploadFile方法来实现;
//图片上传;html
<van-uploader max-count="1"
type="image" file-list="{{ fileList1 }}" use-before-read
bind:before-read="beforeRead1"
bind:after-read="afterRead1" bind:delete="delete1" />
// 图片上传js
beforeRead1(event) {
const {
file,
callback
} = event.detail;
callback(file.type === 'image');
},
delete1(event) {
this.setData({
fileList1: []
})
},
afterRead1(event) {
const {
file
} = event.detail;
let that = this;
let token = wx.getStorageSync('t') || "";
wx.uploadFile({
url: "http://127.0.0.0", // 这里写你们后台服务器的上传路径
method: 'POST',
header: {
token:token,
'content-type': "multipart/form-data; boundary=XXX"
},
filePath: file.url,
name: 'file',
formData: {
bizType: 'SharedStores' //这里是额外的参数,后台不需要删除就行了
},
success(res) {
let list = [{
name: '图片',
url: res.data
}]
that.setData({
fileList1: list
});
},
})
},
文件上传示例
//文件上传;html
<van-uploader max-count="1" accept="file" type="file"
file-list="{{ fileList3 }}" use-before-read
deletable="{{ true }}" bind:before-read="beforeRead3"
bind:after-read="afterRead3" bind:delete="delete3">
<view class="up-btn">+上传文件</view>
</van-uploader>
// 文件上传js
delete3(event) {
this.setData({
fileList3: []
})
},
beforeRead3(event) {
const {
file,
callback
} = event.detail;
callback(file.type === 'file');
},
afterRead3(event) {
const {
file
} = event.detail;
let that = this;
let token = wx.getStorageSync('t') || "";
wx.uploadFile({
url: "http://127.0.0.0", // 这里写你们后台服务器的上传路径
method: 'POST',
header: {
token:token,
'content-type': "multipart/form-data; boundary=XXX"
},
filePath: file.url,
name: 'file',
formData: {
bizType: 'SharedStores' //这里是额外的参数,后台不需要删除就行了
},
success(res) {
let list = [{
name: '文件',
url: res.data
}]
that.setData({
fileList3: list
});
},
})
},