首页 > 解决方案 > 如何将download.pdf重命名为react js中的任何自定义名称

问题描述

我收到base64格式的pdf。当我使用 window.open() pdf 下载打开它时,但 pdf 的名称是 download.pdf。我想自定义名称该 pdf 文件。提前致谢。

   fetch(service_url, {
    method: "POST",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
    },

  }).then(response => response.blob())
    .then(response => {

      var blob=response
      var reader = new window.FileReader();
      reader.readAsDataURL(blob);
      reader.onloadend = function() {
      var base64data = reader.result;

          window.open(base64data);

      }
    })
    .catch(error => {
      console.error(error);
    });

标签: javascriptreactjs

解决方案


我确实在一个项目中创建了一个实用程序,希望这会有所帮助。

exportToJson = el => {
    if (!isEmpty(this.formData)) {
      const obj = encodeURIComponent(JSON.stringify(this.formData, null, '\t'));
      const data = "text/json; charset=utf-8," + "obj";
      const date = new Date();

      const fileName = "customName.json";
      el.target.setAttribute('href', 'data:' + data);
      el.target.setAttribute('download', fileName);
    }
  };

推荐阅读