微信小程序上传图片及文件(上传、下载、删除及预览)
// components/uploaddown/
const app = getApp()
Component({
/**
* 组件的属性列表
*/
properties: {
count: { // 最多选择图片的张数
type: Number,
value: 9,
},
thumb: {
type: Boolean,
value: ''
},
orderShow: {
type: Object,
},
attachment: {
type: Array,
},
orderAttachment: {
type: String,
},
fileDetail: {
type: Boolean,
}
},
/**
* 组件的初始数据
*/
data: {
fileList: [], // 需要上传的图片列表
isAct: false,
isSava: false,
files: [],
loading: false,
storeList: [],
imgModalBox: {
visible: false,
previewImage: '',
imgWidth: 0,
imgHeight: 0,
original: false, // 查看原图
},
tempFilePaths: [], // 上传的附件 图片
storeName: '', // 下载时需要传给路由的文件字段
deleteFilePathName: '', // 获取删除图片路径名
tempUnImgList: [], // 上传的文件列表
itemFilePathName: '', // 获取上传时文件路径名
itemFileUrlName: '', // 获取上传后 后端返回的文件路径名
fileNamePath: '', // 截取数组的path
fileData: [], // 上传文件后获取返回的结果 文件
markFile: '', // 删除文件按钮 文件
// deleFileList: [], // 删除时传给后台数组 文件
allImgList: [],
imageShow: false, // 图片上传完成是 渲染图片
filesShow: false, // 文件上传成功后显示
orderShowUp: {},
titleImg: '',
attachmentImgFile: [], // 区分单据和病例
detailUrl: '',
},
attached() {
const {
orderShow,
orderAttachment,
fileDetail,
} = this.properties;
this.setData({
orderShowUp: orderShow,
})
if (orderAttachment === "order_attachment") {
this.setData({
attachmentImgFile: orderShow.attachment
})
} else if (orderAttachment === "order_patient_attachment") {
this.setData({
attachmentImgFile: orderShow.patient_attachment
})
} else {
this.setData({
attachmentImgFile: orderShow.attachment
})
}
},
/**
* 组件的方法列表
*/
methods: {
uploadAction(e) { // 支持聊天界面上传 文件
const {
orderAttachment,
} = this.properties;
const that = this;
const {
orderShowUp
} = that.data;
wx.chooseMessageFile({
count: 9,
type: 'file',
success(res) {
wx.showToast({ // 显示消息提示框
title: '正在上传...',
icon: 'loading',
mask: true,
duration: 1000
})
const tempFilePaths = res.tempFiles
that.setData({
tempUnImgList: res.tempFiles // 传给后台数据数组
})
var arr = [];
const Token = wx.getStorageSync("token");
let count = tempFilePaths.length;
for (let i = 0; i < tempFilePaths.length; i++) {
const element = tempFilePaths[i];
wx.uploadFile({
url: `${app.host}attachments`,
filePath: tempFilePaths[i].path,
name: 'files[]',
header: {
'Content-Type': 'application/json',
token: `${Token}`
},
formData: {
'from_id': orderShowUp.id,
'from_field': orderAttachment,
'files[]': res.tempFiles,
},
// formData: {
// 'from_id': 28036,
// 'from_field': 'order_attachment',
// 'files[]': ,
// },
success(res) {
if (orderAttachment === 'logistics_attachment') {
app.request({
method: "GET",
url: `logistics/${orderShowUp.id}`,
}).then(res => {
that.setData({
orderShowUp: res.data.data,
attachmentImgFile: res.data.data.attachment
})
}).catch(err => {})
} else {
app.request({
method: "GET",
url: `tumor/order/orders/${orderShowUp.id}`,
}).then(res => {
that.setData({
orderShowUp: res.data.data
})
if (orderAttachment === "order_attachment") {
that.setData({
attachmentImgFile: res.data.data.attachment
})
} else {
that.setData({
attachmentImgFile: res.data.data.patient_attachment
})
}
}).catch(err => {})
}
that.setData({
filesShow: true // 文件上传成功后显示
})
const strData = res.data //返回的结果
var fileDataList = JSON.parse(strData).data;
if (JSON.parse(strData).code !== 0) {
wx.showToast({
title: '文件格式不正确(jpeg,gif,png,pdf,doc,docx,xls,xlsx,ppt,pptx)',
content: '上传图片失败',
showCancel: false,
success: function (res) {}
})
}
for (let j = 0; j < fileDataList.length; j++) {
const fileArray = fileDataList;
const item = fileArray[j];
that.setData({
storeName: item.store_name,
})
for (let k = 0; k < that.data.tempUnImgList.length; k++) {
const itemFileIndex = that.data.tempUnImgList[k];
const itemFilePathName = itemFileIndex.path.slice(11);
that.setData({
itemFilePathName, // 上传前传给服务器的文件 截取后的路径名
itemFileUrlName: item.original_name, // 服务器返回的文件路径名
})
}
if (item.id) {
// 添加缓存数据
wx.setStorageSync('list_file', fileDataList[0])
var valueFile = wx.getStorageSync('list_file');
arr.push(valueFile)
that.setData({
fileData: arr
})
if (count === 1) {
wx.showToast({
title: '上传成功',
icon: '',
mask: true,
duration: 1300
})
} else {
count -= 1;
}
} else {
console.log("有点问题");
}
}
},
fail: function (res) {
wx.showToast({
title: '上传失败',
icon: '',
mask: true,
duration: 1300
})
}
})
}
}
})
},
/**
* 上传附件 支持本地图库上传
* */
uploadup: function (e) {
if (this.data.thumb === false) {
this.setData({
thumb: true
})
}
const {
orderAttachment,
} = this.properties;
let that = this;
const {
orderShowUp
} = that.data;
wx.chooseImage({
count: that.data.count,
sizeType: ['original', 'compressed'],
sourceType: ['album', 'camera'],
success(res) {
// tempFilePath可以作为img标签的src属性显示图片
const tempFilePaths = res.tempFilePaths;
// ({ // 显示消息提示框
// title: '正在上传...',
// icon: 'loading',
// mask: true,
// duration: 1000
// })
wx.showLoading({
title: '正在上传',
})
that.setData({
tempFilePaths: tempFilePaths
})
let count = that.data.tempFilePaths.length;
var arr = [];
for (var j = 0; j < that.data.tempFilePaths.length; j++) {
const Token = wx.getStorageSync("token");
wx.uploadFile({
url: `${app.host}attachments`,
filePath: tempFilePaths[j],
name: 'files[]',
header: {
'Content-Type': 'application/json',
token: `${Token}`
},
formData: {
'from_id': orderShowUp.id,
'from_field': orderAttachment,
'files[]': res.tempFiles,
},
// formData: {
// 'from_id': 28036,
// 'from_field': 'order_attachment',
// 'files[]': tempFilePaths,
// },
success(res) {
if (orderAttachment === 'logistics_attachment') {
app.request({
method: "GET",
url: `logistics/${orderShowUp.id}`,
}).then(res => {
that.setData({
orderShowUp: res.data.data,
attachmentImgFile: res.data.data.attachment
})
}).catch(err => {})
} else {
app.request({
method: "GET",
url: `tumor/order/orders/${orderShowUp.id}`,
}).then(res => {
that.setData({
orderShowUp: res.data.data
})
if (orderAttachment === "order_attachment") {
that.setData({
attachmentImgFile: res.data.data.attachment
})
} else if (orderAttachment === "order_patient_attachment") {
that.setData({
attachmentImgFile: res.data.data.patient_attachment
})
}
}).catch(err => {})
}
that.setData({
imageShow: true // 图片上传完成是 渲染图片
})
//如果是最后一张,则隐藏等待中
// if (count == ) {
// ();
// }
const str = res.data //返回的结果
var pic = JSON.parse(str);
if (count === 1) {
wx.hideLoading()
if (JSON.parse(str).code === 0) {
wx.showToast({
title: '上传成功',
icon: '',
mask: true,
duration: 1300
})
} else {
wx.showToast({
title: '文件格式不正确',
content: '上传图片失败',
showCancel: false,
success: function (res) {}
})
}
} else {
count -= 1;
}
// 添加缓存数据
wx.setStorageSync('list_stutas', pic.data[0])
var valueFile = wx.getStorageSync('list_stutas');
arr.push(valueFile)
that.setData({
fileList: arr
})
},
fail: function (res) {
wx.showToast({
title: '错误提示',
content: '上传图片失败',
showCancel: false,
success: function (res) {}
})
}
})
}
}
})
},
/**
* 预览上传的文件
*/
listenerButtonPreviewImage: function (e) {
// ("submit", ) // 子传父
let index = e.target.dataset.index;
let that = this;
const {
orderAttachment
} = that.data;
if (orderAttachment === "order_attachment") {
const attachment = that.data.orderShowUp.attachment;
that.setData({
attachmentImgFile: attachment
})
} else if (orderAttachment === "order_patient_attachment") {
const patient_attachment = that.data.orderShowUp.patient_attachment;
that.setData({
attachmentImgFile: patient_attachment
})
} else {
const attachment = that.data.orderShowUp.attachment;
that.setData({
attachmentImgFile: attachment
})
}
const Token = wx.getStorageSync("token");
wx.showLoading({ // loading加载
title: '加载中',
})
wx.downloadFile({
url: `${app.host}attachments/${that.data.attachmentImgFile[index].store_name}/download`, //仅为示例,并非真实的资源
// url:`${}sales/attachments`,
// filePath: tempFilePaths[i].path,
header: {
'Content-Type': 'application/json',
token: `${Token}`
},
success(res) {
const arr = [];
const tempFilePath = res.tempFilePath;
arr.push(tempFilePath);
wx.previewImage({ // 在新页面中全屏预览图片
// current: [index], // 当前显示图片的http链接
// urls: , // 需要预览的图片http链接列表
current: tempFilePath, // 当前显示图片的http链接
urls: arr, // 需要预览的图片http链接列表
success: function (res) {
wx.hideLoading()
},
fail: function (res) {
wx.showToast({
title: '预览失败',
icon: '',
mask: true,
duration: 1300
})
}
})
}
})
},
/**
* 点击文件下载
*/
uploadDown: function (e) {
const that = this;
that.setData({
markFile: e.currentTarget.dataset.index
})
const deleteImgIndex = this.data.markFile; // 获取定位的文件index
wx.getSavedFileList({ // 获取文件列表
success(res) {
res.fileList.forEach((val, key) => { // 遍历文件列表里的数据
// 删除存储的垃圾数据
wx.removeSavedFile({
filePath: val.filePath,
})
})
}
})
wx.showToast({ // 显示消息提示框
title: '正在下载...',
icon: 'loading',
mask: true,
duration: 1000
})
// const storeName = ;
const {
orderAttachment
} = that.data;
if (orderAttachment === "order_attachment") {
const attachment = that.data.orderShowUp.attachment;
that.setData({
attachmentImgFile: attachment
})
} else if (orderAttachment === "order_patient_attachment") {
const attachment = that.data.orderShowUp.patient_attachment;
that.setData({
attachmentImgFile: attachment
})
} else {
const attachment = that.data.orderShowUp.attachment;
that.setData({
attachmentImgFile: attachment
})
}
const Token = wx.getStorageSync("token");
wx.downloadFile({
url: `${app.host}attachments/${that.data.attachmentImgFile[deleteImgIndex].store_name}/download`, //仅为示例,并非真实的资源
// url:`${}sales/attachments`,
// filePath: tempFilePaths[i].path,
header: {
'Content-Type': 'application/json',
token: `${Token}`
},
success(res) {
wx.showToast({
title: '下载成功',
icon: '',
mask: true,
duration: 1300
})
const tempFilePath = res.tempFilePath;
// 保存文件
wx.saveFile({
tempFilePath,
success: function (res) {
const savedFilePath = res.savedFilePath;
// 打开文件
wx.openDocument({
filePath: savedFilePath,
success: function (res) {
console.log('打开文档成功')
},
});
},
fail: function (err) {
console.log('保存失败:', err)
}
});
// 只要服务器有响应数据,就会把响应内容写入文件并进入 success 回调,业务需要自行判断是否下载到了想要的内容
if (res.statusCode === 200) {
// ({
// filePath:
// })
wx.showToast({
title: '下载成功',
icon: '',
mask: true,
duration: 1500
})
}
},
fail: function (err) {
console.log('下载失败:', err);
},
})
},
/**
* 删除当前文件 或者图片
*/
setDelArr: function (file) {
const that = this;
that.setData({
markFile: file.currentTarget.dataset.index
})
const {
orderShowUp
} = that.data;
const deleteImgIndex = this.data.markFile; // 获取定位的文件index
const deleFileList = that.data.tempUnImgList; // 获取上传时传给后端的list
const fileList = that.data.fileData; // 获取上传时后端传来的文件
const {
orderAttachment
} = that.data;
if (orderAttachment === "order_attachment") {
const attachment = that.data.orderShowUp.attachment;
that.setData({
attachmentImgFile: attachment
})
} else if (orderAttachment === "order_patient_attachment") {
const patient_attachment = that.data.orderShowUp.patient_attachment;
that.setData({
attachmentImgFile: patient_attachment
})
} else {
const attachment = that.data.orderShowUp.attachment;
that.setData({
attachmentImgFile: attachment
})
}
wx.showModal({
title: '确认删除',
content: '你确定要删除吗?',
success: res => {
if (res.confirm) {
wx.showToast({ // 显示消息提示框
title: '正在删除...',
icon: 'loading',
mask: true,
duration: 1000
})
const Token = wx.getStorageSync("token");
// if (fileList[0].name === (11)) { // pc端使用
// if ((11) === attachment[deleteImgIndex].original_name) { // pc端使用
app.request({
url: `attachments/${that.data.attachmentImgFile[deleteImgIndex].store_name}/delete`,
method: 'POST', // 判断请求类型,除了值等于'post'外,其余值均视作get
data: {
from_id: orderShowUp.id,
from_field: orderAttachment,
},
header: {
'Content-Type': 'application/json',
token: `${Token}`
},
}).then(res => {
if (orderAttachment === 'logistics_attachment') {
app.request({
method: "GET",
url: `logistics/${orderShowUp.id}`,
}).then(res => {
that.setData({
orderShowUp: res.data.data
})
if (res.data.data.attachment.length === 0) {
that.setData({
attachmentImgFile: []
})
}
}).catch(err => {})
} else {
app.request({
method: "GET",
url: `tumor/order/orders/${orderShowUp.id}`,
}).then(res => {
that.setData({
orderShowUp: res.data.data
})
if (orderAttachment === "order_attachment" && !res.data.data.attachment) {
that.setData({
attachmentImgFile: []
})
} else if (!res.data.data.patient_attachment) {
that.setData({
attachmentImgFile: []
})
}
}).catch(err => {})
}
wx.showToast({
title: '删除成功',
icon: '',
mask: true,
duration: 1300
})
// newFiles = (item => item.original_name !== deleFileList[deleteImgIndex].(11));
})
// }
// }
}
}
})
},
},
})