axios 上传(上传既包括二进制文件,又包括json数据)、下载(下载流数据另存为数据,流数据转换为json)

时间:2024-10-01 18:43:07

下载axios配置

  1. function downloadPolicy(data) {
  2. return request({
  3. url: '/api/invo/goods/downloadPolicy',
  4. method: 'post',
  5. data,
  6. responseType: 'blob'
  7. });
  8. }
'
运行

流数据转换为excel文件并下载到本地

  1. downloadPolicy(data).then(res => {
  2. // new Blob([data])用来创建URL的file对象或者blob对象
  3. const url = window.URL.createObjectURL(new Blob([res]));
  4. // 生成一个a标签
  5. const link = document.createElement("a");
  6. link.style.display = "none";
  7. link.href = url;
  8. link.download = "待批量开具清单.xlsx";
  9. document.body.appendChild(link);
  10. link.click();
  11. }).catch(() => {
  12. this.$loading.hide();
  13. });

包含json数据的流转换为json

  1. var reader = new FileReader();
  2. console.log('reader', reader);
  3. reader.readAsText(res, 'utf-8');
  4. reader.onload = () => {
  5. const parseData = JSON.parse(reader.result);
  6. console.log('parse', parseData);
  7. if (parseData.status === -1) {
  8. this.$message.error(parseData.statusText);
  9. }
  10. };

上传axios配置

  1. function uploadBatchPolicy(data) {
  2. return request({
  3. url: '/api/invo/invoice/uploadBatchPolicy',
  4. method: 'post',
  5. data,
  6. headers: { "Content-Type": "multipart/form-data" }
  7. });
  8. }
'
运行

上传(添加文件二进制数据和json数据)

  1. const formData = new FormData();
  2. // 通过append向form对象添加数据
  3. formData.append("file", rawFile);
  4. formData.append("name", 'wfz');
  5. this.$loading.show();
  6. uploadBatchPolicy(formData).then(res => {
  7. this.$loading.hide();
  8. if (res.status === 0) {
  9. this.$message.success('上传成功!');
  10. this.uuid = res.data.uuid;
  11. this.searchForm.policyNoFileLineNum = res.data.policyCount;
  12. } else {
  13. this.$message.error(res.statusText);
  14. }
  15. }).catch(() => {
  16. this.$loading.hide();
  17. });