Anchor download attribute created with javascript not working on iOS Chrome

狂风中的少年 提交于 2020-12-13 19:00:33

问题


I have a video/mp4 file saved in AWS S3 bucket, which should be downloaded from a client device (phone or computer) when the user clicks on an icon. I first make a request using fetch, and then create a blob object from the response. Next, I create an anchor element using javascript, I attach the href attribute and trigger it's click as on the code below:

fetch(url, {
      headers: new Headers({
        'Content-Disposition': "attachment; filename='file-name.mp4'",
      }),
    }).then((response): void => {
      if (!response.ok) {
        console.log('Error', response);
      }

      response.blob().then((blob): void => {
        let videoUrl = window.URL.createObjectURL(blob);
        let a = document.createElement('a');
        document.body.appendChild(a);
        a.href = videoUrl;
        a.download = 'file-name.mp4';
        a.target = '_blank';
        a.click();
        document.body.removeChild(a);
      });
    });

When testing this code, it works on Android Chrome and iOS Safari, but it doesn't on iOS Chrome. I can see that a request is fired but nothing happens, not even a new tab gets open. I have tried some other approaches like using FileSaver.js library, also tried directly the FileReader like on the examples below, but still doesn't work.

fetch(url, {
      headers: new Headers({
        'Content-Disposition': "attachment; filename='file-name.mp4'",
      }),
    }).then((response): void => {
      if (!response.ok) {
        console.log('Error', response);
      }

      response.blob().then((blob): void => {
        FileSaver.saveAs(blob, 'file-name.mp4');
      });
    });


fetch(url, {
      headers: new Headers({
        'Content-Disposition': "attachment; filename='file-name.mp4'",
      }),
    }).then((response): void => {
      if (!response.ok) {
        console.log('Error', response);
      }

      response.blob().then((blob): void => {
        let reader = new FileReader();

        reader.readAsDataURL(blob);

        reader.onloadend = (): void => {
            if (reader.result) {
                let url = reader.result.toString();

                window.open(url, '_blank');
           }
        };
      });
    });

The blob type is 'application/octet-stream'. Has anyone ever had a similar issue or has any other new approach idea? Thank you!

来源:https://stackoverflow.com/questions/63848034/anchor-download-attribute-created-with-javascript-not-working-on-ios-chrome

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!