当前位置:   article > 正文

在小程序中使用formdata上传数据,可实现多文件上传

在小程序中使用formdata上传数据,可实现多文件上传

1.下载formdata

GitHub - zlyboy/wx-formdata: 在小程序中使用formdata上传数据,可实现多文件上传

2. 前端页面

  1. <uni-collapse class='collapse' ref='collapse'>
  2. <uni-collapse-item v-for="(item, index) in attachmentList"
  3. :key="index"
  4. :title="item.dictName" class='collapse-item' title-border='show' :border='false'>
  5. <view class="content">
  6. <FileUploader :attachment="item" :uniqueId='uniqueId' @handleHeight='handleHeight' v-model="item.attachmentIds" />
  7. </view>
  8. </uni-collapse-item>
  9. </uni-collapse>
  10. attachmentList: [
  11. {
  12. "id": 1,
  13. "dictCode": "XCDCTP",
  14. "dictName": "现场调查图片",
  15. "categoryCode": ",XCDCTP,",
  16. "servicePhase": "sb",
  17. "attachmentIds":[]
  18. },
  19. ],
  20. isFetching: false,
  21. uniqueId:'',

3.组件

  1. <template>
  2. <view>
  3. <view class="file_list">
  4. <view class="file_list__box" v-for="(file,index) in fileList" :key="index" @click="fileActive(file)">
  5. <uni-icons type="paperclip" size="15"></uni-icons>
  6. <text>{{file.name}}</text>
  7. <view class="delete_file" @click.stop="deleteFile(index,file)">
  8. <uni-icons type="clear" size="16"></uni-icons>
  9. </view>
  10. </view>
  11. </view>
  12. <view class="uni-file-picker__container">
  13. <view class="file-picker__box" v-for="(image,index) in imageList" :key="index">
  14. <view class="file-picker__box-content">
  15. <image class="file-image" :src="image.url" mode="aspectFill" :data-src="image.url"
  16. @click.stop="previewImage">
  17. </image>
  18. <view class="icon-del-box" @click.stop="deleteImage(index,image)">
  19. <view class="icon-del"></view>
  20. <view class="icon-del rotate"></view>
  21. </view>
  22. </view>
  23. </view>
  24. <view class="file-picker__box" v-for="(video,index) in videoList" :key="index">
  25. <view class="file-picker__box-content">
  26. <video class="file-image" :src="video.url"></video>
  27. <view class="icon-del-box" @click.stop="deleteVideo(index,video)">
  28. <view class="icon-del"></view>
  29. <view class="icon-del rotate"></view>
  30. </view>
  31. </view>
  32. </view>
  33. <view v-if="VideoOfImagesShow" class="file-picker__box">
  34. <view class="file-picker__box-content is-add" @tap="chooseVideoImage">
  35. <slot>
  36. <view class="icon-add"></view>
  37. <view class="icon-add rotate"></view>
  38. </slot>
  39. </view>
  40. </view>
  41. </view>
  42. </view>
  43. </template>
  44. <script>
  45. import {
  46. uploadFile,saveAttachInfo,deleteAttachment,uploadFileByName
  47. } from '@/service/api.js'
  48. import {
  49. showToast
  50. } from '@/utils/index.js'
  51. import {
  52. BASE_API_URL
  53. } from '@/common/config.js'
  54. import {
  55. appStorage
  56. } from '@/utils/storage.js'
  57. const FormData = require('@/utils/formdata/index.js')
  58. export default {
  59. props: {
  60. attachment: Object,
  61. uniqueId:String
  62. },
  63. data() {
  64. return {
  65. imageList: [], //图片
  66. videoList: [], //视频存放
  67. fileList: [], //文件
  68. ids: [],
  69. sourceTypeIndex: 2,
  70. sourceType: ['拍摄', '相册', '拍摄或相册'],
  71. VideoOfImagesShow: true,
  72. cameraList: [{
  73. value: 'back',
  74. name: '后置摄像头',
  75. checked: 'true'
  76. },
  77. {
  78. value: 'front',
  79. name: '前置摄像头'
  80. },
  81. ],
  82. cameraIndex: 0,
  83. videoSuffix: ["AVI", "mov", "rmvb", "rm", "FLV", "mp4", "3GP"],
  84. suffix:['jpeg','png','jpg','JPG'],
  85. pageOfficeSuffix: ['doc', 'docx', 'xls', 'xlsx','pdf','PDF']
  86. }
  87. },
  88. created() {
  89. this.imageList = []; //图片
  90. this.videoList = []; //视频存放
  91. this.fileList = []; //文件
  92. this.ids = [];
  93. if(this.attachment.fileList.length>0){
  94. this.setAttachmentData(this.attachment.fileList)
  95. }
  96. },
  97. watch: {
  98. ids(val) {
  99. this.$emit('input', val)
  100. },
  101. },
  102. methods: {
  103. chooseImages() {
  104. console.log('图片')
  105. let that = this;
  106. // 上传图片
  107. uni.chooseImage({
  108. count: 1, //默认9
  109. // sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
  110. sourceType: ['album', 'camera'], //从相册选择
  111. success: async (response) => {
  112. console.log(response)
  113. let result = await that.fileSizeIsLessLimitSize(response.tempFilePaths[0])
  114. if (result) {
  115. showToast('图片质量过大')
  116. return;
  117. }
  118. uni.showLoading({
  119. mask: true
  120. })
  121. let igmFile = response.tempFilePaths;
  122. console.log(igmFile,'igmFile');
  123. console.log("===============================");
  124. let requestData = {
  125. "masterld":'1772150445546708994',
  126. "formGroupCode":'XMPG',
  127. "categoryCode":',XCDCTP,',
  128. "categoryName":'现场图片'
  129. }
  130. let token = appStorage.get('token');
  131. wx.uploadFile({
  132. url: `接口地址`,
  133. filePath: igmFile[0],
  134. name: 'file',
  135. formData: requestData,
  136. header: {
  137. 'Blade-Auth': token
  138. },
  139. success: res=>{
  140. console.log(res)
  141. uni.hideLoading()
  142. if (res.code === '200') {
  143. let imgUrls = res.data
  144. let info = {
  145. url: BASE_API_URL + '/minio' + imgUrls.link.substring(that.findCharAt(
  146. imgUrls.link, '/', 2)),
  147. id: imgUrls.attachmentId
  148. }
  149. that.imageList = that.imageList.concat(info);
  150. that.ids = that.ids.concat(imgUrls.attachmentId);
  151. that.$emit('handleHeight')
  152. that.$_saveAttachInfo(imgUrls.attachmentId,imgUrls.link,imgUrls.originalName)
  153. // if (that.ids.length >= 5) {
  154. // that.VideoOfImagesShow = false;
  155. // } else {
  156. // that.VideoOfImagesShow = true;
  157. // }
  158. } else {
  159. showToast('操作失败')
  160. }
  161. }
  162. })
  163. // const formData = new FormData();
  164. // formData.append("masterld",'1772150445546708994')
  165. // formData.append("formGroupCode",'XMPG')
  166. // formData.append("categoryCode",',XCDCTP,')
  167. // formData.append("categoryName",'TP')
  168. // // 这里上传文件
  169. // formData.appendFile("file",igmFile[0], "file")
  170. // let data = formData.getData();
  171. // console.log('转化之后的数据111111',data);
  172. // let token = appStorage.get('token');
  173. // console.log("token",token);
  174. // // const [err, res] = await uploadFile(data);
  175. // // console.log(res,1666666);
  176. // wx.request({
  177. // // url: 'http://61.243.2.188:8000/api/miniapp-rc-gz/fileUpload/upload',
  178. // url: 'https://gznd.longersoftware.com/api/miniapp-rc-gz/fileUpload/upload',
  179. // method:'POST',
  180. // header: {
  181. // 'content-type': data.contentType,
  182. // 'Blade-Auth': token
  183. // },
  184. // data: data.buffer,
  185. // success: function (res) {
  186. // console.log(res,1777777);
  187. // // //上传成功
  188. // // that.setData({
  189. // // portrait: res.data.data
  190. // // });
  191. // // wx.showModal({
  192. // // title: '信息',
  193. // // content: res.data.message,
  194. // // confirmText: '确认'
  195. // // }); //showModal
  196. // }
  197. // });
  198. // const [err, res] = await uploadFile(
  199. // {url:'https://gznd.longersoftware.com',
  200. // filePath:igmFile,
  201. // data:{
  202. // masterld:'1772150445546708994',
  203. // formGroupCode:'XMPG',
  204. // categoryCode:",XCDCTP,",
  205. // categoryName:"现场调查图片,"
  206. // }
  207. // })
  208. // const [err, res] = uploadFile(
  209. // 'https://gznd.longersoftware.com',
  210. // igmFile,
  211. // {
  212. // masterld:'1772150445546708994',
  213. // formGroupCode:'XMPG',
  214. // categoryCode:",XCDCTP,",
  215. // categoryName:"现场调查图片,"
  216. // }
  217. // ).then
  218. // console.log('uploadFile',err, res);
  219. // uni.hideLoading()
  220. // if (err) {
  221. // showToast('操作失败')
  222. // return
  223. // }
  224. // if (res.code === 200) {
  225. // let imgUrls = res.data
  226. // let info = {
  227. // url: BASE_API_URL + '/minio' + imgUrls.link.substring(that.findCharAt(
  228. // imgUrls.link, '/', 2)),
  229. // id: imgUrls.attachId
  230. // }
  231. // that.imageList = that.imageList.concat(info);
  232. // that.ids = that.ids.concat(imgUrls.attachId);
  233. // that.$emit('handleHeight')
  234. // that.$_saveAttachInfo(imgUrls.attachId,imgUrls.link,imgUrls.originalName)
  235. // // if (that.ids.length >= 5) {
  236. // // that.VideoOfImagesShow = false;
  237. // // } else {
  238. // // that.VideoOfImagesShow = true;
  239. // // }
  240. // } else {
  241. // showToast(res.msg)
  242. // }
  243. },
  244. });
  245. },
  246. // importZcExcel(file){
  247. // // console.log('-file:',file,'-fileList:',fileList)
  248. // const formData = new FormData();
  249. // formData.append('excel', file.raw);
  250. // // console.log('文件:',formData);
  251. // let that=this;
  252. // importZc(formData).then(res => {
  253. // let data=res.data;
  254. // // console.log('xxxx:',data)
  255. // if(data && data.success){
  256. // this.$message.success(data.data);
  257. // that.searchChange();
  258. // }else{
  259. // this.$message.error('message:',data.msg);
  260. // }
  261. // });
  262. // },
  263. chooseVideoImage() {
  264. console.log('this.attachment',this.attachment)
  265. console.log('this.uniqueId',this.uniqueId)
  266. uni.showActionSheet({
  267. title: "选择上传类型",
  268. itemList: ['图片', '视频', '文件'],
  269. success: (res) => {
  270. console.log(res)
  271. if (res.tapIndex == 0) {
  272. this.chooseImages()
  273. } else if (res.tapIndex == 1) {
  274. this.chooseVideo()
  275. } else {
  276. this.chooseFile()
  277. }
  278. }
  279. })
  280. },
  281. chooseFile() {
  282. console.log('文件')
  283. let vm = this;
  284. wx.chooseMessageFile({
  285. count: 1,
  286. type: 'file',
  287. success: async (response) => {
  288. console.log('res--选取文件--', response);
  289. let result = await vm.fileSizeIsLessLimitSize(response.tempFiles[0].path)
  290. if (result) {
  291. showToast('文件质量过大')
  292. return;
  293. }
  294. let igmFile = response.tempFiles;
  295. uni.showLoading({
  296. mask: true
  297. })
  298. let name=igmFile[0].name;
  299. const [err, res] = await uploadFileByName(igmFile[0].path, {fileName:name})
  300. console.log('uploadFileByName',err, res);
  301. uni.hideLoading()
  302. if (err) {
  303. showToast('操作失败')
  304. return
  305. }
  306. console.log('上传文件', res)
  307. if (res.code === 200) {
  308. let files = res.data
  309. let info = {
  310. url: BASE_API_URL + '/minio' + files.link.substring(vm.findCharAt(files
  311. .link, '/', 2)),
  312. id: files.attachId,
  313. name:name
  314. // name:'文件'
  315. }
  316. vm.fileList = vm.fileList.concat(info);
  317. vm.ids = vm.ids.concat(files.attachId);
  318. vm.$emit('handleHeight')
  319. vm.$_saveAttachInfo(files.attachId,files.link,files.originalName)
  320. } else {
  321. showToast(res.msg)
  322. }
  323. }
  324. })
  325. },
  326. chooseImages2() {
  327. console.log('图片')
  328. let that = this;
  329. // 上传图片
  330. uni.chooseImage({
  331. count: 1, //默认9
  332. // sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
  333. sourceType: ['album', 'camera'], //从相册选择
  334. success: async (response) => {
  335. console.log(response)
  336. let result = await that.fileSizeIsLessLimitSize(response.tempFilePaths[0])
  337. if (result) {
  338. showToast('图片质量过大')
  339. return;
  340. }
  341. uni.showLoading({
  342. mask: true
  343. })
  344. console.log(response,'response');
  345. let igmFile = response.tempFilePaths;
  346. console.log(igmFile,'igmFile');
  347. // const formData = new FormData();
  348. // formData.append("file",igmFile)
  349. // const [err, res] = await uploadFile(
  350. // {url:'https://gznd.longersoftware.com',
  351. // filePath:igmFile,
  352. // data:{
  353. // masterld:'1772150445546708994',
  354. // formGroupCode:'XMPG',
  355. // categoryCode:",XCDCTP,",
  356. // categoryName:"现场调查图片,"
  357. // }
  358. // })
  359. const [err, res] = uploadFile(
  360. 'https://gznd.longersoftware.com',
  361. igmFile,
  362. {
  363. masterld:'1772150445546708994',
  364. formGroupCode:'XMPG',
  365. categoryCode:",XCDCTP,",
  366. categoryName:"现场调查图片,"
  367. }
  368. ).then
  369. // const [err, res] = await uploadFile('1772150445546708994','XMPG',formData,",XCDCTP,","现场调查图片,")
  370. // const [err, res] = await uploadFile(igmFile[0], {})
  371. console.log('uploadFile',err, res);
  372. uni.hideLoading()
  373. if (err) {
  374. showToast('操作失败')
  375. return
  376. }
  377. if (res.code === 200) {
  378. let imgUrls = res.data
  379. let info = {
  380. url: BASE_API_URL + '/minio' + imgUrls.link.substring(that.findCharAt(
  381. imgUrls.link, '/', 2)),
  382. id: imgUrls.attachId
  383. }
  384. that.imageList = that.imageList.concat(info);
  385. that.ids = that.ids.concat(imgUrls.attachId);
  386. that.$emit('handleHeight')
  387. that.$_saveAttachInfo(imgUrls.attachId,imgUrls.link,imgUrls.originalName)
  388. // if (that.ids.length >= 5) {
  389. // that.VideoOfImagesShow = false;
  390. // } else {
  391. // that.VideoOfImagesShow = true;
  392. // }
  393. } else {
  394. showToast(res.msg)
  395. }
  396. },
  397. });
  398. },
  399. chooseVideo() {
  400. console.log('视频')
  401. let that = this;
  402. // 上传视频
  403. uni.chooseVideo({
  404. maxDuration: 60,
  405. count: 1,
  406. camera: this.cameraList[this.cameraIndex].value,
  407. sourceType: ['album'],
  408. success: async (responent) => {
  409. console.log(responent)
  410. let videoFile = responent.tempFilePath;
  411. console.log(videoFile)
  412. let result = await that.fileSizeIsLessLimitSize(responent.tempFilePath)
  413. if (result) {
  414. showToast('图片质量过大')
  415. return;
  416. }
  417. uni.showLoading({
  418. mask: true
  419. })
  420. const [err, res] = await uploadFile(videoFile, {})
  421. uni.hideLoading()
  422. console.log(res)
  423. if (err) {
  424. showToast('操作失败')
  425. return
  426. }
  427. if (res.code === 200) {
  428. let videoUrls = res.data //百度支持
  429. let info = {
  430. url: BASE_API_URL + '/minio' + videoUrls.link.substring(that.findCharAt(
  431. videoUrls.link, '/', 2)),
  432. id: videoUrls.attachId
  433. }
  434. that.videoList = that.videoList.concat(info);
  435. that.ids = that.ids.concat(videoUrls.attachId);
  436. that.$emit('handleHeight')
  437. that.$_saveAttachInfo(videoUrls.attachId,videoUrls.link,videoUrls.originalName)
  438. // if (that.ids.length >= 5) {
  439. // that.VideoOfImagesShow = false;
  440. // } else {
  441. // that.VideoOfImagesShow = true;
  442. // }
  443. } else {
  444. showToast(res.msg)
  445. }
  446. // this.src = responent.tempFilePath; //头条
  447. }
  448. })
  449. },
  450. previewImage: function(e) {
  451. //预览图片
  452. var current = e.target.dataset.src
  453. let list = [];
  454. this.imageList.forEach((item) => {
  455. list.push(item.url)
  456. })
  457. uni.previewImage({
  458. current: current,
  459. urls: list
  460. })
  461. },
  462. deleteImage(index, item) {
  463. console.log(item)
  464. let that = this;
  465. uni.showModal({
  466. title: "提示",
  467. content: "是否要删除该图片",
  468. success: async (res) => {
  469. if (res.confirm) {
  470. const [error, response] = await deleteAttachment({attachmentId:item.id})
  471. console.log(response)
  472. if (error) {
  473. showToast('操作失败')
  474. return
  475. }
  476. if (response.code === 200) {
  477. that.imageList.splice(index, 1);
  478. that.ids.splice(that.ids.indexOf(item.id), 1);
  479. // if (that.ids.length >= 5) {
  480. // that.VideoOfImagesShow = false;
  481. // } else {
  482. // that.VideoOfImagesShow = true;
  483. // }
  484. showToast(response.msg)
  485. that.$emit('handleHeight')
  486. }
  487. }
  488. }
  489. })
  490. },
  491. deleteVideo(index, item) {
  492. let that = this;
  493. uni.showModal({
  494. title: "提示",
  495. content: "是否要删除此视频",
  496. success: async (res) => {
  497. if (res.confirm) {
  498. const [error, response] = await deleteAttachment({attachmentId:item.id})
  499. if (error) {
  500. showToast('操作失败')
  501. return
  502. }
  503. if (response.code === 200) {
  504. that.videoList.splice(index, 1);
  505. that.ids.splice(that.ids.indexOf(item.id), 1);
  506. // if (that.ids.length >= 5) {
  507. // that.VideoOfImagesShow = false;
  508. // } else {
  509. // that.VideoOfImagesShow = true;
  510. // }
  511. showToast(response.msg)
  512. that.$emit('handleHeight')
  513. }
  514. }
  515. }
  516. })
  517. },
  518. fileActive(file) {
  519. let that=this;
  520. uni.showActionSheet({
  521. title: "文件操作",
  522. itemList: ['查看'],
  523. success: (res) => {
  524. console.log(res)
  525. if (res.tapIndex == 0) {
  526. console.log('查看', file)
  527. this.downloadFilePreview(file)
  528. }
  529. }
  530. })
  531. },
  532. downloadFilePreview (file) {
  533. uni.showLoading({
  534. mask: true
  535. })
  536. wx.downloadFile({
  537. url: file.url, // 这里换上自己的pdf地址
  538. header: {
  539. 'content-type': 'application/json'
  540. },
  541. success: function (res) {
  542. console.log(res)
  543. var Path = res.tempFilePath // 返回的文件临时地址,用于后面打开本地预览所用
  544. wx.openDocument({
  545. filePath: Path,
  546. success: function (res) {
  547. uni.hideLoading()
  548. },
  549. fail: function (res) {
  550. showToast('打开失败')
  551. }
  552. })
  553. },
  554. fail: function (res) {
  555. showToast('下载失败')
  556. }
  557. })
  558. },
  559. deleteFile(index, item) {
  560. let that = this;
  561. uni.showModal({
  562. title: "提示",
  563. content: "是否要删除此文件",
  564. success: async (res) => {
  565. if (res.confirm) {
  566. const [error, response] = await deleteAttachment({attachmentId:item.id})
  567. if (error) {
  568. showToast('操作失败')
  569. return
  570. }
  571. if (response.code === 200) {
  572. that.fileList.splice(index, 1);
  573. that.ids.splice(that.ids.indexOf(item.id), 1);
  574. that.$emit('handleHeight')
  575. showToast(response.msg)
  576. }
  577. }
  578. }
  579. })
  580. },
  581. async $_saveAttachInfo(id,link,originalName){
  582. let data={
  583. bladeAttachmentPath:link,
  584. bladeAttachmentId:id,
  585. dictCode:this.attachment.dictCode,
  586. categoryCode:this.attachment.categoryCode,
  587. dictName:this.attachment.dictName,
  588. uniqueId:this.uniqueId,
  589. originalName:originalName
  590. }
  591. const [err, res] = await saveAttachInfo(data)
  592. if (err) {
  593. return
  594. }
  595. if (res.code === 200) {
  596. }
  597. },
  598. //判断文件大小是否满足需求,limitSize的单位是kb
  599. fileSizeIsLessLimitSize(filePath) {
  600. //获取文件信息
  601. let result = false;
  602. return new Promise((resolve, reject) => {
  603. uni.getFileInfo({
  604. filePath: filePath,
  605. success: (res) => {
  606. console.log("文件大小", res.size / 1024, 'kb');
  607. if (res.size / 1024 > 1024 * 10) {
  608. result = true;
  609. }
  610. resolve(result);
  611. },
  612. fail: (err) => {
  613. reject(result)
  614. }
  615. })
  616. })
  617. },
  618. findCharAt(str, cha, num) {
  619. var x = str.indexOf(cha);
  620. for (var i = 0; i < num; i++) {
  621. x = str.indexOf(cha, x + 1);
  622. }
  623. return x;
  624. },
  625. setAttachmentData(data){
  626. console.log('图片数据',data)
  627. let that=this;
  628. data.forEach(item=>{
  629. let suffix = item.originalName.substring(item.originalName.lastIndexOf('.') + 1, item.originalName.length);
  630. let info = {
  631. // url: BASE_API_URL + '/minio' + item.bladeAttachmentPath.substring(that.findCharAt(item
  632. // .bladeAttachmentPath, '/', 2)),
  633. url: BASE_API_URL + '/minio' + item.bladeAttachmentPath,
  634. id: item.bladeAttachmentId,
  635. name:item.originalName
  636. }
  637. that.ids = that.ids.concat(item.bladeAttachmentId);
  638. if(this.suffix.indexOf(suffix)>=0){
  639. that.imageList = that.imageList.concat(info);
  640. } else if(this.videoSuffix.indexOf(suffix)>=0){
  641. that.videoList = that.videoList.concat(info);
  642. }else if(this.pageOfficeSuffix.indexOf(suffix)>=0){
  643. that.fileList = that.fileList.concat(info);
  644. }
  645. })
  646. }
  647. }
  648. }
  649. </script>
  650. <style>
  651. .uni-file-picker__container {
  652. display: flex;
  653. box-sizing: border-box;
  654. flex-wrap: wrap;
  655. margin: -5rpx;
  656. justify-content: start;
  657. }
  658. .file-picker__box {
  659. position: relative;
  660. width: 200rpx;
  661. height: 0;
  662. padding-top: 200rpx;
  663. box-sizing: border-box;
  664. }
  665. .file-picker__box-content {
  666. position: absolute;
  667. top: 0;
  668. right: 0;
  669. bottom: 0;
  670. left: 0;
  671. margin: 10rpx;
  672. border: 1rpx #eee solid;
  673. border-radius: 5px;
  674. overflow: hidden;
  675. }
  676. .file-image {
  677. width: 100%;
  678. height: 100%;
  679. }
  680. .is-add {
  681. display: flex;
  682. align-items: center;
  683. justify-content: center;
  684. }
  685. .icon-add {
  686. width: 50rpx;
  687. height: 5rpx;
  688. background-color: #f1f1f1;
  689. border-radius: 2px;
  690. }
  691. .rotate {
  692. position: absolute;
  693. transform: rotate(90deg);
  694. }
  695. .icon-del-box {
  696. display: flex;
  697. align-items: center;
  698. justify-content: center;
  699. position: absolute;
  700. top: 3rpx;
  701. right: 3rpx;
  702. height: 26rpx;
  703. width: 26rpx;
  704. border-radius: 50%;
  705. background-color: rgba(0, 0, 0, 0.5);
  706. z-index: 2;
  707. transform: rotate(-45deg);
  708. }
  709. .icon-del {
  710. width: 15rpx;
  711. height: 2rpx;
  712. background-color: #fff;
  713. border-radius: 2rpx;
  714. }
  715. ,
  716. .file_list__box {
  717. margin-bottom: 20rpx;
  718. display: flex;
  719. align-items: center;
  720. position: relative;
  721. }
  722. .file_list__box text {
  723. font-size: 32rpx;
  724. padding-left: 5rpx;
  725. color: #949F94;
  726. overflow: hidden;
  727. word-break: break-all;
  728. /* break-all(允许在单词内换行。) */
  729. text-overflow: ellipsis;
  730. /* 超出部分省略号 */
  731. display: -webkit-box;
  732. /** 对象作为伸缩盒子模型显示 **/
  733. -webkit-box-orient: vertical;
  734. /** 设置或检索伸缩盒对象的子元素的排列方式 **/
  735. -webkit-line-clamp: 1;
  736. /** 显示的行数 **/
  737. }
  738. .file_list__box .delete_file {
  739. position: absolute;
  740. right: -15rpx;
  741. z-index: 2;
  742. }
  743. </style>

4.注意:文件和上传视频代码未修改

5.formdata

 

const mimeMap = require('./mimeMap.js')

function FormData(){

  let fileManager = wx.getFileSystemManager();

  let data = {};

  let files = [];

  this.append = (name, value)=>{

    data[name] = value;

    return true;

  }

  this.appendFile = (name, path, fileName)=>{

    let buffer = fileManager.readFileSync(path);

    if(Object.prototype.toString.call(buffer).indexOf("ArrayBuffer") < 0){

      return false;

    }

    if(!fileName){

      fileName = getFileNameFromPath(path);

    }

    files.push({

      name: name,

      buffer: buffer,

      fileName: fileName

    });

    return true;

  }

  this.getData = ()=>convert(data, files)

}

function getFileNameFromPath(path){

  let idx=path.lastIndexOf("/");

  return path.substr(idx+1);

}

function convert(data, files){

  let boundaryKey = 'wxmpFormBoundary' + randString(); // 数据分割符,一般是随机的字符串

  let boundary = '--' + boundaryKey;

  let endBoundary = boundary + '--';

  let postArray = [];

  //拼接参数

  if(data && Object.prototype.toString.call(data) == "[object Object]"){

    for(let key in data){

      postArray = postArray.concat(formDataArray(boundary, key, data[key]));

    }

  }

  //拼接文件

  if(files && Object.prototype.toString.call(files) == "[object Array]"){

    for(let i in files){

      let file = files[i];

      postArray = postArray.concat(formDataArray(boundary, file.name, file.buffer, file.fileName));

    }

  }

  //结尾

  let endBoundaryArray = [];

  endBoundaryArray.push(...endBoundary.toUtf8Bytes());

  postArray = postArray.concat(endBoundaryArray);

  return {

    contentType: 'multipart/form-data; boundary=' + boundaryKey,

    buffer: new Uint8Array(postArray).buffer

  }

}

function randString() {

  var result = '';

  var chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

  for (var i = 17; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)];

  return result;

}

function formDataArray(boundary, name, value, fileName){

  let dataString = '';

  let isFile = !!fileName;

  dataString += boundary + '\r\n';

  dataString += 'Content-Disposition: form-data; name="' + name + '"';

  if (isFile){

    dataString += '; filename="' + fileName + '"' + '\r\n';

    dataString += 'Content-Type: ' + getFileMime(fileName) + '\r\n\r\n';

  }

  else{

    dataString += '\r\n\r\n';

    dataString += value;

  }

  var dataArray = [];

  dataArray.push(...dataString.toUtf8Bytes());

  if (isFile) {

    let fileArray = new Uint8Array(value);

    dataArray = dataArray.concat(Array.prototype.slice.call(fileArray));

  }

  dataArray.push(..."\r".toUtf8Bytes());

  dataArray.push(..."\n".toUtf8Bytes());

  return dataArray;

}

function getFileMime(fileName){

  let idx = fileName.lastIndexOf(".");

  let mime = mimeMap[fileName.substr(idx)];

  return mime?mime:"application/octet-stream"

}

String.prototype.toUtf8Bytes = function(){

  var str = this;

  var bytes = [];

  for (var i = 0; i < str.length; i++) {

    bytes.push(...str.utf8CodeAt(i));

    if (str.codePointAt(i) > 0xffff) {

      i++;

    }

  }

  return bytes;

}

String.prototype.utf8CodeAt = function(i) {

  var str = this;

  var out = [], p = 0;

  var c = str.charCodeAt(i);

  if (c < 128) {

    out[p++] = c;

  } else if (c < 2048) {

    out[p++] = (c >> 6) | 192;

    out[p++] = (c & 63) | 128;

  } else if (

      ((c & 0xFC00) == 0xD800) && (i + 1) < str.length &&

      ((str.charCodeAt(i + 1) & 0xFC00) == 0xDC00)) {

    // Surrogate Pair

    c = 0x10000 + ((c & 0x03FF) << 10) + (str.charCodeAt(++i) & 0x03FF);

    out[p++] = (c >> 18) | 240;

    out[p++] = ((c >> 12) & 63) | 128;

    out[p++] = ((c >> 6) & 63) | 128;

    out[p++] = (c & 63) | 128;

  } else {

    out[p++] = (c >> 12) | 224;

    out[p++] = ((c >> 6) & 63) | 128;

    out[p++] = (c & 63) | 128;

  }

  return out;

};


 

module.exports = FormData;

6.mimeMap.js

module.exports = {

  "0.001": "application/x-001",

  "0.323": "text/h323",

  "0.907": "drawing/907",

  ".acp": "audio/x-mei-aac",

  ".aif": "audio/aiff",

  ".aiff": "audio/aiff",

  ".asa": "text/asa",

  ".asp": "text/asp",

  ".au": "audio/basic",

  ".awf": "application/vnd.adobe.workflow",

  ".bmp": "application/x-bmp",

  ".c4t": "application/x-c4t",

  ".cal": "application/x-cals",

  ".cdf": "application/x-netcdf",

  ".cel": "application/x-cel",

  ".cg4": "application/x-g4",

  ".cit": "application/x-cit",

  ".cml": "text/xml",

  ".cmx": "application/x-cmx",

  ".crl": "application/pkix-crl",

  ".csi": "application/x-csi",

  ".cut": "application/x-cut",

  ".dbm": "application/x-dbm",

  ".dcd": "text/xml",

  ".der": "application/x-x509-ca-cert",

  ".dib": "application/x-dib",

  ".doc": "application/msword",

  ".drw": "application/x-drw",

  ".dwf": "Model/vnd.dwf",

  ".dwg": "application/x-dwg",

  ".dxf": "application/x-dxf",

  ".emf": "application/x-emf",

  ".ent": "text/xml",

  ".eps": "application/x-ps",

  ".etd": "application/x-ebx",

  ".fax": "image/fax",

  ".fif": "application/fractals",

  ".frm": "application/x-frm",

  ".gbr": "application/x-gbr",

  ".gif": "image/gif",

  ".gp4": "application/x-gp4",

  ".hmr": "application/x-hmr",

  ".hpl": "application/x-hpl",

  ".hrf": "application/x-hrf",

  ".htc": "text/x-component",

  ".html": "text/html",

  ".htx": "text/html",

  ".ico": "image/x-icon",

  ".iff": "application/x-iff",

  ".igs": "application/x-igs",

  ".img": "application/x-img",

  ".isp": "application/x-internet-signup",

  ".java": "java/*",

  ".jpe": "image/jpeg",

  ".jpeg": "image/jpeg",

  ".jpg": "application/x-jpg",

  ".jsp": "text/html",

  ".lar": "application/x-laplayer-reg",

  ".lavs": "audio/x-liquid-secure",

  ".lmsff": "audio/x-la-lms",

  ".ltr": "application/x-ltr",

  ".m2v": "video/x-mpeg",

  ".m4e": "video/mpeg4",

  ".man": "application/x-troff-man",

  ".mdb": "application/msaccess",

  ".mfp": "application/x-shockwave-flash",

  ".mhtml": "message/rfc822",

  ".mid": "audio/mid",

  ".mil": "application/x-mil",

  ".mnd": "audio/x-musicnet-download",

  ".mocha": "application/x-javascript",

  ".mp1": "audio/mp1",

  ".mp2v": "video/mpeg",

  ".mp4": "video/mpeg4",

  ".mpd": "application/vnd.ms-project",

  ".mpeg": "video/mpg",

  ".mpga": "audio/rn-mpeg",

  ".mps": "video/x-mpeg",

  ".mpv": "video/mpg",

  ".mpw": "application/vnd.ms-project",

  ".mtx": "text/xml",

  ".net": "image/pnetvue",

  ".nws": "message/rfc822",

  ".out": "application/x-out",

  ".p12": "application/x-pkcs12",

  ".p7c": "application/pkcs7-mime",

  ".p7r": "application/x-pkcs7-certreqresp",

  ".pc5": "application/x-pc5",

  ".pcl": "application/x-pcl",

  ".pdf": "application/pdf",

  ".pdx": "application/vnd.adobe.pdx",

  ".pgl": "application/x-pgl",

  ".pko": "application/vnd.ms-pki.pko",

  ".plg": "text/html",

  ".plt": "application/x-plt",

  ".png": "application/x-png",

  ".ppa": "application/vnd.ms-powerpoint",

  ".pps": "application/vnd.ms-powerpoint",

  ".ppt": "application/x-ppt",

  ".prf": "application/pics-rules",

  ".prt": "application/x-prt",

  ".ps": "application/postscript",

  ".pwz": "application/vnd.ms-powerpoint",

  ".ra": "audio/vnd.rn-realaudio",

  ".ras": "application/x-ras",

  ".rdf": "text/xml",

  ".red": "application/x-red",

  ".rjs": "application/vnd.rn-realsystem-rjs",

  ".rlc": "application/x-rlc",

  ".rm": "application/vnd.rn-realmedia",

  ".rmi": "audio/mid",

  ".rmm": "audio/x-pn-realaudio",

  ".rms": "application/vnd.rn-realmedia-secure",

  ".rmx": "application/vnd.rn-realsystem-rmx",

  ".rp": "image/vnd.rn-realpix",

  ".rsml": "application/vnd.rn-rsml",

  ".rtf": "application/msword",

  ".rv": "video/vnd.rn-realvideo",

  ".sat": "application/x-sat",

  ".sdw": "application/x-sdw",

  ".slb": "application/x-slb",

  ".slk": "drawing/x-slk",

  ".smil": "application/smil",

  ".snd": "audio/basic",

  ".sor": "text/plain",

  ".spl": "application/futuresplash",

  ".ssm": "application/streamingmedia",

  ".stl": "application/vnd.ms-pki.stl",

  ".sty": "application/x-sty",

  ".swf": "application/x-shockwave-flash",

  ".tg4": "application/x-tg4",

  ".tif": "image/tiff",

  ".tiff": "image/tiff",

  ".top": "drawing/x-top",

  ".tsd": "text/xml",

  ".uin": "application/x-icq",

  ".vcf": "text/x-vcard",

  ".vdx": "application/vnd.visio",

  ".vpg": "application/x-vpeg005",

  ".vsd": "application/x-vsd",

  ".vst": "application/vnd.visio",

  ".vsw": "application/vnd.visio",

  ".vtx": "application/vnd.visio",

  ".wav": "audio/wav",

  ".wb1": "application/x-wb1",

  ".wb3": "application/x-wb3",

  ".wiz": "application/msword",

  ".wk4": "application/x-wk4",

  ".wks": "application/x-wks",

  ".wma": "audio/x-ms-wma",

  ".wmf": "application/x-wmf",

  ".wmv": "video/x-ms-wmv",

  ".wmz": "application/x-ms-wmz",

  ".wpd": "application/x-wpd",

  ".wpl": "application/vnd.ms-wpl",

  ".wr1": "application/x-wr1",

  ".wrk": "application/x-wrk",

  ".ws2": "application/x-ws",

  ".wsdl": "text/xml",

  ".xdp": "application/vnd.adobe.xdp",

  ".xfd": "application/vnd.adobe.xfd",

  ".xhtml": "text/html",

  ".xls": "application/x-xls",

  ".xml": "text/xml",

  ".xq": "text/xml",

  ".xquery": "text/xml",

  ".xsl": "text/xml",

  ".xwd": "application/x-xwd",

  ".sis": "application/vnd.symbian.install",

  ".x_t": "application/x-x_t",

  ".apk": "application/vnd.android.package-archive",

  "0.301": "application/x-301",

  "0.906": "application/x-906",

  ".a11": "application/x-a11",

  ".ai": "application/postscript",

  ".aifc": "audio/aiff",

  ".anv": "application/x-anv",

  ".asf": "video/x-ms-asf",

  ".asx": "video/x-ms-asf",

  ".avi": "video/avi",

  ".biz": "text/xml",

  ".bot": "application/x-bot",

  ".c90": "application/x-c90",

  ".cat": "application/vnd.ms-pki.seccat",

  ".cdr": "application/x-cdr",

  ".cer": "application/x-x509-ca-cert",

  ".cgm": "application/x-cgm",

  ".class": "java/*",

  ".cmp": "application/x-cmp",

  ".cot": "application/x-cot",

  ".crt": "application/x-x509-ca-cert",

  ".css": "text/css",

  ".dbf": "application/x-dbf",

  ".dbx": "application/x-dbx",

  ".dcx": "application/x-dcx",

  ".dgn": "application/x-dgn",

  ".dll": "application/x-msdownload",

  ".dot": "application/msword",

  ".dtd": "text/xml",

  ".dwf": "application/x-dwf",

  ".dxb": "application/x-dxb",

  ".edn": "application/vnd.adobe.edn",

  ".eml": "message/rfc822",

  ".epi": "application/x-epi",

  ".eps": "application/postscript",

  ".exe": "application/x-msdownload",

  ".fdf": "application/vnd.fdf",

  ".fo": "text/xml",

  ".g4": "application/x-g4",

  ".tif": "image/tiff",

  ".gl2": "application/x-gl2",

  ".hgl": "application/x-hgl",

  ".hpg": "application/x-hpgl",

  ".hqx": "application/mac-binhex40",

  ".hta": "application/hta",

  ".htm": "text/html",

  ".htt": "text/webviewhtml",

  ".icb": "application/x-icb",

  ".ico": "application/x-ico",

  ".ig4": "application/x-g4",

  ".iii": "application/x-iphone",

  ".ins": "application/x-internet-signup",

  ".IVF": "video/x-ivf",

  ".jfif": "image/jpeg",

  ".jpe": "application/x-jpe",

  ".jpg": "image/jpeg",

  ".js": "application/x-javascript",

  ".la1": "audio/x-liquid-file",

  ".latex": "application/x-latex",

  ".lbm": "application/x-lbm",

  ".ls": "application/x-javascript",

  ".m1v": "video/x-mpeg",

  ".m3u": "audio/mpegurl",

  ".mac": "application/x-mac",

  ".math": "text/xml",

  ".mdb": "application/x-mdb",

  ".mht": "message/rfc822",

  ".mi": "application/x-mi",

  ".midi": "audio/mid",

  ".mml": "text/xml",

  ".mns": "audio/x-musicnet-stream",

  ".movie": "video/x-sgi-movie",

  ".mp2": "audio/mp2",

  ".mp3": "audio/mp3",

  ".mpa": "video/x-mpg",

  ".mpe": "video/x-mpeg",

  ".mpg": "video/mpg",

  ".mpp": "application/vnd.ms-project",

  ".mpt": "application/vnd.ms-project",

  ".mpv2": "video/mpeg",

  ".mpx": "application/vnd.ms-project",

  ".mxp": "application/x-mmxp",

  ".nrf": "application/x-nrf",

  ".odc": "text/x-ms-odc",

  ".p10": "application/pkcs10",

  ".p7b": "application/x-pkcs7-certificates",

  ".p7m": "application/pkcs7-mime",

  ".p7s": "application/pkcs7-signature",

  ".pci": "application/x-pci",

  ".pcx": "application/x-pcx",

  ".pdf": "application/pdf",

  ".pfx": "application/x-pkcs12",

  ".pic": "application/x-pic",

  ".pl": "application/x-perl",

  ".pls": "audio/scpls",

  ".png": "image/png",

  ".pot": "application/vnd.ms-powerpoint",

  ".ppm": "application/x-ppm",

  ".ppt": "application/vnd.ms-powerpoint",

  ".pr": "application/x-pr",

  ".prn": "application/x-prn",

  ".ps": "application/x-ps",

  ".ptn": "application/x-ptn",

  ".r3t": "text/vnd.rn-realtext3d",

  ".ram": "audio/x-pn-realaudio",

  ".rat": "application/rat-file",

  ".rec": "application/vnd.rn-recording",

  ".rgb": "application/x-rgb",

  ".rjt": "application/vnd.rn-realsystem-rjt",

  ".rle": "application/x-rle",

  ".rmf": "application/vnd.adobe.rmf",

  ".rmj": "application/vnd.rn-realsystem-rmj",

  ".rmp": "application/vnd.rn-rn_music_package",

  ".rmvb": "application/vnd.rn-realmedia-vbr",

  ".rnx": "application/vnd.rn-realplayer",

  ".rpm": "audio/x-pn-realaudio-plugin",

  ".rt": "text/vnd.rn-realtext",

  ".rtf": "application/x-rtf",

  ".sam": "application/x-sam",

  ".sdp": "application/sdp",

  ".sit": "application/x-stuffit",

  ".sld": "application/x-sld",

  ".smi": "application/smil",

  ".smk": "application/x-smk",

  ".sol": "text/plain",

  ".spc": "application/x-pkcs7-certificates",

  ".spp": "text/xml",

  ".sst": "application/vnd.ms-pki.certstore",

  ".stm": "text/html",

  ".svg": "text/xml",

  ".tdf": "application/x-tdf",

  ".tga": "application/x-tga",

  ".tif": "application/x-tif",

  ".tld": "text/xml",

  ".torrent": "application/x-bittorrent",

  ".txt": "text/plain",

  ".uls": "text/iuls",

  ".vda": "application/x-vda",

  ".vml": "text/xml",

  ".vsd": "application/vnd.visio",

  ".vss": "application/vnd.visio",

  ".vst": "application/x-vst",

  ".vsx": "application/vnd.visio",

  ".vxml": "text/xml",

  ".wax": "audio/x-ms-wax",

  ".wb2": "application/x-wb2",

  ".wbmp": "image/vnd.wap.wbmp",

  ".wk3": "application/x-wk3",

  ".wkq": "application/x-wkq",

  ".wm": "video/x-ms-wm",

  ".wmd": "application/x-ms-wmd",

  ".wml": "text/vnd.wap.wml",

  ".wmx": "video/x-ms-wmx",

  ".wp6": "application/x-wp6",

  ".wpg": "application/x-wpg",

  ".wq1": "application/x-wq1",

  ".wri": "application/x-wri",

  ".ws": "application/x-ws",

  ".wsc": "text/scriptlet",

  ".wvx": "video/x-ms-wvx",

  ".xdr": "text/xml",

  ".xfdf": "application/vnd.adobe.xfdf",

  ".xls": "application/vnd.ms-excel",

  ".xlw": "application/x-xlw",

  ".xpl": "audio/scpls",

  ".xql": "text/xml",

  ".xsd": "text/xml",

  ".xslt": "text/xml",

  ".x_b": "application/x-x_b",

  ".sisx": "application/vnd.symbian.install",

  ".ipa": "application/vnd.iphone",

  ".xap": "application/x-silverlight-app",

  ".zip": "application/x-zip-compressed",

}

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/381821
推荐阅读
相关标签
  

闽ICP备14008679号