当前位置:   article > 正文

在小程序中使用formdata上传数据,可实现多文件上传_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. },
  164. });
  165. },
  166. // importZcExcel(file){
  167. // // console.log('-file:',file,'-fileList:',fileList)
  168. // const formData = new FormData();
  169. // formData.append('excel', file.raw);
  170. // // console.log('文件:',formData);
  171. // let that=this;
  172. // importZc(formData).then(res => {
  173. // let data=res.data;
  174. // // console.log('xxxx:',data)
  175. // if(data && data.success){
  176. // this.$message.success(data.data);
  177. // that.searchChange();
  178. // }else{
  179. // this.$message.error('message:',data.msg);
  180. // }
  181. // });
  182. // },
  183. chooseVideoImage() {
  184. console.log('this.attachment',this.attachment)
  185. console.log('this.uniqueId',this.uniqueId)
  186. uni.showActionSheet({
  187. title: "选择上传类型",
  188. itemList: ['图片', '视频', '文件'],
  189. success: (res) => {
  190. console.log(res)
  191. if (res.tapIndex == 0) {
  192. this.chooseImages()
  193. } else if (res.tapIndex == 1) {
  194. this.chooseVideo()
  195. } else {
  196. this.chooseFile()
  197. }
  198. }
  199. })
  200. },
  201. chooseFile() {
  202. console.log('文件')
  203. let vm = this;
  204. wx.chooseMessageFile({
  205. count: 1,
  206. type: 'file',
  207. success: async (response) => {
  208. console.log('res--选取文件--', response);
  209. let result = await vm.fileSizeIsLessLimitSize(response.tempFiles[0].path)
  210. if (result) {
  211. showToast('文件质量过大')
  212. return;
  213. }
  214. let igmFile = response.tempFiles;
  215. uni.showLoading({
  216. mask: true
  217. })
  218. let name=igmFile[0].name;
  219. const [err, res] = await uploadFileByName(igmFile[0].path, {fileName:name})
  220. console.log('uploadFileByName',err, res);
  221. uni.hideLoading()
  222. if (err) {
  223. showToast('操作失败')
  224. return
  225. }
  226. console.log('上传文件', res)
  227. if (res.code === 200) {
  228. let files = res.data
  229. let info = {
  230. url: BASE_API_URL + '/minio' + files.link.substring(vm.findCharAt(files
  231. .link, '/', 2)),
  232. id: files.attachId,
  233. name:name
  234. // name:'文件'
  235. }
  236. vm.fileList = vm.fileList.concat(info);
  237. vm.ids = vm.ids.concat(files.attachId);
  238. vm.$emit('handleHeight')
  239. vm.$_saveAttachInfo(files.attachId,files.link,files.originalName)
  240. } else {
  241. showToast(res.msg)
  242. }
  243. }
  244. })
  245. },
  246. chooseImages2() {
  247. console.log('图片')
  248. let that = this;
  249. // 上传图片
  250. uni.chooseImage({
  251. count: 1, //默认9
  252. // sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
  253. sourceType: ['album', 'camera'], //从相册选择
  254. success: async (response) => {
  255. console.log(response)
  256. let result = await that.fileSizeIsLessLimitSize(response.tempFilePaths[0])
  257. if (result) {
  258. showToast('图片质量过大')
  259. return;
  260. }
  261. uni.showLoading({
  262. mask: true
  263. })
  264. console.log(response,'response');
  265. let igmFile = response.tempFilePaths;
  266. console.log(igmFile,'igmFile');
  267. const [err, res] = uploadFile(
  268. 'https://gznd.longersoftware.com',
  269. igmFile,
  270. {
  271. masterld:'1772150445546708994',
  272. formGroupCode:'XMPG',
  273. categoryCode:",XCDCTP,",
  274. categoryName:"现场调查图片,"
  275. }
  276. ).then
  277. // const [err, res] = await uploadFile('1772150445546708994','XMPG',formData,",XCDCTP,","现场调查图片,")
  278. // const [err, res] = await uploadFile(igmFile[0], {})
  279. console.log('uploadFile',err, res);
  280. uni.hideLoading()
  281. if (err) {
  282. showToast('操作失败')
  283. return
  284. }
  285. if (res.code === 200) {
  286. let imgUrls = res.data
  287. let info = {
  288. url: BASE_API_URL + '/minio' + imgUrls.link.substring(that.findCharAt(
  289. imgUrls.link, '/', 2)),
  290. id: imgUrls.attachId
  291. }
  292. that.imageList = that.imageList.concat(info);
  293. that.ids = that.ids.concat(imgUrls.attachId);
  294. that.$emit('handleHeight')
  295. that.$_saveAttachInfo(imgUrls.attachId,imgUrls.link,imgUrls.originalName)
  296. // if (that.ids.length >= 5) {
  297. // that.VideoOfImagesShow = false;
  298. // } else {
  299. // that.VideoOfImagesShow = true;
  300. // }
  301. } else {
  302. showToast(res.msg)
  303. }
  304. },
  305. });
  306. },
  307. chooseVideo() {
  308. console.log('视频')
  309. let that = this;
  310. // 上传视频
  311. uni.chooseVideo({
  312. maxDuration: 60,
  313. count: 1,
  314. camera: this.cameraList[this.cameraIndex].value,
  315. sourceType: ['album'],
  316. success: async (responent) => {
  317. console.log(responent)
  318. let videoFile = responent.tempFilePath;
  319. console.log(videoFile)
  320. let result = await that.fileSizeIsLessLimitSize(responent.tempFilePath)
  321. if (result) {
  322. showToast('图片质量过大')
  323. return;
  324. }
  325. uni.showLoading({
  326. mask: true
  327. })
  328. const [err, res] = await uploadFile(videoFile, {})
  329. uni.hideLoading()
  330. console.log(res)
  331. if (err) {
  332. showToast('操作失败')
  333. return
  334. }
  335. if (res.code === 200) {
  336. let videoUrls = res.data //百度支持
  337. let info = {
  338. url: BASE_API_URL + '/minio' + videoUrls.link.substring(that.findCharAt(
  339. videoUrls.link, '/', 2)),
  340. id: videoUrls.attachId
  341. }
  342. that.videoList = that.videoList.concat(info);
  343. that.ids = that.ids.concat(videoUrls.attachId);
  344. that.$emit('handleHeight')
  345. that.$_saveAttachInfo(videoUrls.attachId,videoUrls.link,videoUrls.originalName)
  346. // if (that.ids.length >= 5) {
  347. // that.VideoOfImagesShow = false;
  348. // } else {
  349. // that.VideoOfImagesShow = true;
  350. // }
  351. } else {
  352. showToast(res.msg)
  353. }
  354. // this.src = responent.tempFilePath; //头条
  355. }
  356. })
  357. },
  358. previewImage: function(e) {
  359. //预览图片
  360. var current = e.target.dataset.src
  361. let list = [];
  362. this.imageList.forEach((item) => {
  363. list.push(item.url)
  364. })
  365. uni.previewImage({
  366. current: current,
  367. urls: list
  368. })
  369. },
  370. deleteImage(index, item) {
  371. console.log(item)
  372. let that = this;
  373. uni.showModal({
  374. title: "提示",
  375. content: "是否要删除该图片",
  376. success: async (res) => {
  377. if (res.confirm) {
  378. const [error, response] = await deleteAttachment({attachmentId:item.id})
  379. console.log(response)
  380. if (error) {
  381. showToast('操作失败')
  382. return
  383. }
  384. if (response.code === 200) {
  385. that.imageList.splice(index, 1);
  386. that.ids.splice(that.ids.indexOf(item.id), 1);
  387. // if (that.ids.length >= 5) {
  388. // that.VideoOfImagesShow = false;
  389. // } else {
  390. // that.VideoOfImagesShow = true;
  391. // }
  392. showToast(response.msg)
  393. that.$emit('handleHeight')
  394. }
  395. }
  396. }
  397. })
  398. },
  399. deleteVideo(index, item) {
  400. let that = this;
  401. uni.showModal({
  402. title: "提示",
  403. content: "是否要删除此视频",
  404. success: async (res) => {
  405. if (res.confirm) {
  406. const [error, response] = await deleteAttachment({attachmentId:item.id})
  407. if (error) {
  408. showToast('操作失败')
  409. return
  410. }
  411. if (response.code === 200) {
  412. that.videoList.splice(index, 1);
  413. that.ids.splice(that.ids.indexOf(item.id), 1);
  414. // if (that.ids.length >= 5) {
  415. // that.VideoOfImagesShow = false;
  416. // } else {
  417. // that.VideoOfImagesShow = true;
  418. // }
  419. showToast(response.msg)
  420. that.$emit('handleHeight')
  421. }
  422. }
  423. }
  424. })
  425. },
  426. fileActive(file) {
  427. let that=this;
  428. uni.showActionSheet({
  429. title: "文件操作",
  430. itemList: ['查看'],
  431. success: (res) => {
  432. console.log(res)
  433. if (res.tapIndex == 0) {
  434. console.log('查看', file)
  435. this.downloadFilePreview(file)
  436. }
  437. }
  438. })
  439. },
  440. downloadFilePreview (file) {
  441. uni.showLoading({
  442. mask: true
  443. })
  444. wx.downloadFile({
  445. url: file.url, // 这里换上自己的pdf地址
  446. header: {
  447. 'content-type': 'application/json'
  448. },
  449. success: function (res) {
  450. console.log(res)
  451. var Path = res.tempFilePath // 返回的文件临时地址,用于后面打开本地预览所用
  452. wx.openDocument({
  453. filePath: Path,
  454. success: function (res) {
  455. uni.hideLoading()
  456. },
  457. fail: function (res) {
  458. showToast('打开失败')
  459. }
  460. })
  461. },
  462. fail: function (res) {
  463. showToast('下载失败')
  464. }
  465. })
  466. },
  467. deleteFile(index, item) {
  468. let that = this;
  469. uni.showModal({
  470. title: "提示",
  471. content: "是否要删除此文件",
  472. success: async (res) => {
  473. if (res.confirm) {
  474. const [error, response] = await deleteAttachment({attachmentId:item.id})
  475. if (error) {
  476. showToast('操作失败')
  477. return
  478. }
  479. if (response.code === 200) {
  480. that.fileList.splice(index, 1);
  481. that.ids.splice(that.ids.indexOf(item.id), 1);
  482. that.$emit('handleHeight')
  483. showToast(response.msg)
  484. }
  485. }
  486. }
  487. })
  488. },
  489. async $_saveAttachInfo(id,link,originalName){
  490. let data={
  491. bladeAttachmentPath:link,
  492. bladeAttachmentId:id,
  493. dictCode:this.attachment.dictCode,
  494. categoryCode:this.attachment.categoryCode,
  495. dictName:this.attachment.dictName,
  496. uniqueId:this.uniqueId,
  497. originalName:originalName
  498. }
  499. const [err, res] = await saveAttachInfo(data)
  500. if (err) {
  501. return
  502. }
  503. if (res.code === 200) {
  504. }
  505. },
  506. //判断文件大小是否满足需求,limitSize的单位是kb
  507. fileSizeIsLessLimitSize(filePath) {
  508. //获取文件信息
  509. let result = false;
  510. return new Promise((resolve, reject) => {
  511. uni.getFileInfo({
  512. filePath: filePath,
  513. success: (res) => {
  514. console.log("文件大小", res.size / 1024, 'kb');
  515. if (res.size / 1024 > 1024 * 10) {
  516. result = true;
  517. }
  518. resolve(result);
  519. },
  520. fail: (err) => {
  521. reject(result)
  522. }
  523. })
  524. })
  525. },
  526. findCharAt(str, cha, num) {
  527. var x = str.indexOf(cha);
  528. for (var i = 0; i < num; i++) {
  529. x = str.indexOf(cha, x + 1);
  530. }
  531. return x;
  532. },
  533. setAttachmentData(data){
  534. console.log('图片数据',data)
  535. let that=this;
  536. data.forEach(item=>{
  537. let suffix = item.originalName.substring(item.originalName.lastIndexOf('.') + 1, item.originalName.length);
  538. let info = {
  539. // url: BASE_API_URL + '/minio' + item.bladeAttachmentPath.substring(that.findCharAt(item
  540. // .bladeAttachmentPath, '/', 2)),
  541. url: BASE_API_URL + '/minio' + item.bladeAttachmentPath,
  542. id: item.bladeAttachmentId,
  543. name:item.originalName
  544. }
  545. that.ids = that.ids.concat(item.bladeAttachmentId);
  546. if(this.suffix.indexOf(suffix)>=0){
  547. that.imageList = that.imageList.concat(info);
  548. } else if(this.videoSuffix.indexOf(suffix)>=0){
  549. that.videoList = that.videoList.concat(info);
  550. }else if(this.pageOfficeSuffix.indexOf(suffix)>=0){
  551. that.fileList = that.fileList.concat(info);
  552. }
  553. })
  554. }
  555. }
  556. }
  557. </script>
  558. <style>
  559. .uni-file-picker__container {
  560. display: flex;
  561. box-sizing: border-box;
  562. flex-wrap: wrap;
  563. margin: -5rpx;
  564. justify-content: start;
  565. }
  566. .file-picker__box {
  567. position: relative;
  568. width: 200rpx;
  569. height: 0;
  570. padding-top: 200rpx;
  571. box-sizing: border-box;
  572. }
  573. .file-picker__box-content {
  574. position: absolute;
  575. top: 0;
  576. right: 0;
  577. bottom: 0;
  578. left: 0;
  579. margin: 10rpx;
  580. border: 1rpx #eee solid;
  581. border-radius: 5px;
  582. overflow: hidden;
  583. }
  584. .file-image {
  585. width: 100%;
  586. height: 100%;
  587. }
  588. .is-add {
  589. display: flex;
  590. align-items: center;
  591. justify-content: center;
  592. }
  593. .icon-add {
  594. width: 50rpx;
  595. height: 5rpx;
  596. background-color: #f1f1f1;
  597. border-radius: 2px;
  598. }
  599. .rotate {
  600. position: absolute;
  601. transform: rotate(90deg);
  602. }
  603. .icon-del-box {
  604. display: flex;
  605. align-items: center;
  606. justify-content: center;
  607. position: absolute;
  608. top: 3rpx;
  609. right: 3rpx;
  610. height: 26rpx;
  611. width: 26rpx;
  612. border-radius: 50%;
  613. background-color: rgba(0, 0, 0, 0.5);
  614. z-index: 2;
  615. transform: rotate(-45deg);
  616. }
  617. .icon-del {
  618. width: 15rpx;
  619. height: 2rpx;
  620. background-color: #fff;
  621. border-radius: 2rpx;
  622. }
  623. ,
  624. .file_list__box {
  625. margin-bottom: 20rpx;
  626. display: flex;
  627. align-items: center;
  628. position: relative;
  629. }
  630. .file_list__box text {
  631. font-size: 32rpx;
  632. padding-left: 5rpx;
  633. color: #949F94;
  634. overflow: hidden;
  635. word-break: break-all;
  636. /* break-all(允许在单词内换行。) */
  637. text-overflow: ellipsis;
  638. /* 超出部分省略号 */
  639. display: -webkit-box;
  640. /** 对象作为伸缩盒子模型显示 **/
  641. -webkit-box-orient: vertical;
  642. /** 设置或检索伸缩盒对象的子元素的排列方式 **/
  643. -webkit-line-clamp: 1;
  644. /** 显示的行数 **/
  645. }
  646. .file_list__box .delete_file {
  647. position: absolute;
  648. right: -15rpx;
  649. z-index: 2;
  650. }
  651. </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/Cpp五条/article/detail/586658
推荐阅读
相关标签
  

闽ICP备14008679号