NodeJS 当我们知道完整路径时,如何使用Axios上传文件?

mzillmmw  于 2022-12-18  发布在  Node.js
关注(0)|答案(1)|浏览(308)

我尝试使用Axios上传文件,但我只想使用文件路径的字符串。使用下面的代码,它是工作:

<input
  id="select-files"
  style="visibility: hidden"
  type="file"
  multiple
  @change="handleFilesUpload($event)"
/>

但是当我尝试使用createReadStream时,它不起作用。我想知道如何将这些路径文件转换为event.target.files
我已经尝试上面的代码,但它不工作:

let data = {
  THE_FILE: "",
  BRANCH_ID: this.$store.state.starv.localUser.DOCTOR_INFO["BRANCH_ID"],
  ACC_NO: this.locationItem["ACC_NO"],
  CHART_NO: this.locationItem["CHART_NO"],
  EMP_ID: this.$store.state.starv.localUser.DOCTOR_INFO["EMP_ID"],
  CO_EMP_ID: this.doctorList.toString(),
  ST: "telehealthclient",
  NEW_NAME: "",
  MAID: LocalData.getComputerId(),
}

/*
  Iterate over any file sent over appending the files to the form data.
*/
data["THE_FILE"] = window.fs.createReadStream(filePath)

let bodyFormData = new FormData()

// if (THE_FILE) {
//     bodyFormData.append("THE_FILE", THE_FILE)
// }

for (let key in data) {
  bodyFormData.append(key, data[key])
}
bfnvny8b

bfnvny8b1#

我已经找到了解决这个问题的办法,我们将做以下:
1.将文件编码为base64

base64_encode(file) {
      // read binary data
      let bitmap = window.fs.readFileSync(file);
      // convert binary data to base64 encoded string
      return new Buffer(bitmap).toString("base64");
    },

1.从base64创建一个file-url对象

dataURLtoFile(dataurl, filename) {
      const arr = dataurl.split(",");
      const mime = arr[0].match(/:(.*?);/)[1];
      const bstr = atob(arr[1]);
      let n = bstr.length;
      const u8arr = new Uint8Array(n);
      while (n) {
        u8arr[n - 1] = bstr.charCodeAt(n - 1);
        n -= 1; // to make eslint happy
      }
      return new File([u8arr], filename, { type: mime });
    },

1.从表单数据库创建表单数据使用Axios上传
1.多部分形式
完整代码如下

base64_encode(file) {
      // read binary data
      let bitmap = window.fs.readFileSync(file);
      // convert binary data to base64 encoded string
      return new Buffer(bitmap).toString("base64");
    },

    dataURLtoFile(dataurl, filename) {
      const arr = dataurl.split(",");
      const mime = arr[0].match(/:(.*?);/)[1];
      const bstr = atob(arr[1]);
      let n = bstr.length;
      const u8arr = new Uint8Array(n);
      while (n) {
        u8arr[n - 1] = bstr.charCodeAt(n - 1);
        n -= 1; // to make eslint happy
      }
      return new File([u8arr], filename, { type: mime });
    },

    uploadScreenRecord(data) {
      return new Promise((resolve, reject) => {
        // #1 Convert to base64 first
        let base64_video = this.base64_encode(data.file);

        // #2 Create file url object from base64
        let filename = path.parse(data.file).base;
        let fileURLobject = this.dataURLtoFile(
          "data:video/mp4;base64," + base64_video,
          filename
        );

        // #3 Create form data from form-data libary
        const formData = new formData_();
        formData.append("THE_FILE", fileURLobject, filename);
        for (let key in data) {
          if (key != "file") {
            formData.append(key, data[key]);
          }
        }

        // #4 Send to server
        let url;
        if (SETTING.imedtacDomain.hostname == undefined) {
          url = SETTING.webservice.imedtacProtocol + "//" + defaultDomain;
        } else {
          url =
            SETTING.webservice.imedtacProtocol + "//" + SETTING.imedtacDomain.hostname;
        }

        axios
          .post(url + SETTING.imedtacAPI.uploadFile.URL, formData, {
            headers: {
              "Access-Control-Allow-Origin": "*",
              "Content-Type": "multipart/form-data",
            },
            timeout: 30000,
          })
          .then(function (response) {
            //Return Patient
            console.log("[File debug] This is upload file response %o", response);
            if (response.data.success) {
              resolve(response.data.FILE_URL);
            } else {
              reject(response.data.message + "  screen record upload error");
            }
          })
          .catch(function (error) {
            reject(error);
          });
      });
    },

    submitFilesTest() {
      return new Promise((resolve, reject) => {
        //Data
        let data = {
          file: "/Users/ivanhutomo/Downloads/B0120221214151850_A.mp4",
          BRANCH_ID: "xxx",
          ACC_NO: "xx",
          CHART_NO: "xx",
          EMP_ID: "xx",
          CO_EMP_ID: "xx",
          ST: "xx",
          NEW_NAME: "",
          MAID: "xx",
        };

        this.uploadScreenRecord(data)
          .then((response) => {
            logger.debug("[File debug]  File upload URL %o", response);
            resolve(response);
          })
          .catch((error) => {
            logger.debug("[File debug]  File %o", error);
            reject(error);
          });
      });
    },

submitFilesTest()

相关问题