Home > Mobile >  How to change the extension name of a file before downloading?
How to change the extension name of a file before downloading?

Time:10-25

I have a video file hosted which looks like this:

https://cdn.shopify.com/s/files/1/0664/3037/0044/files/video

Right now, the video file has no extension at all. Using Javascript, how can I download the file with .mp4 extension. I need a way to change its filename to [filename].mp4 and then download.

I tried the following but it downloads the file without the extension.

function downloadURI(uri, name) {
  var link = document.createElement("a");
  link.download = name;
  link.href = uri;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  delete link;
}



downloadURI("https://cdn.shopify.com/s/files/1/0664/3037/0044/files/video", "video.mp4");

CodePudding user response:

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#attr-download

download only works for same-origin URLs, or the blob: and data: schemes. If the Content-Disposition header has different information from the download attribute, resulting behavior may differ:

If the header specifies a filename, it takes priority over a filename specified in the download attribute.
If the header specifies a disposition of inline, Chrome and Firefox prioritize the attribute and treat it as a download. Old Firefox versions (before 82) prioritize the header and will display the content inline.

I tried your code on a different origin and it wouldn't download but simply redirect to the URL, also it doesn't send Content-Disposition, so it looks like since you're testing this on a different origin, it just redirects to the file link, discarding download because it's on a different origin, and your browser is configured to download it. My browser is configured to autoplay videos.

However, I see the URL you provided has CORS *, meaning any origin can access it. So, an alternative you can do is, download the file, and create a blob, then send download to browser.

function downloadURI(uri, name) {
   fetch(uri).then((response) => response.blob())
   .then((blobresp) => {
       var blob = new Blob([blobresp], {type: "octet/stream"});
       var url = window.URL.createObjectURL(blob);

       var link = document.createElement("a");
       link.download = name;
       link.href = url;
       document.body.appendChild(link);
       link.click();
       document.body.removeChild(link);
       delete link;
   })
}

downloadURI("https://cdn.shopify.com/s/files/1/0664/3037/0044/files/video", "video.mp4");

CodePudding user response:

const myRenamedFile = new File([myFile], 'my-file-final-1-really.txt');

Taken from this website which may be a better at explaining than me:

https://pqina.nl/blog/rename-a-file-with-javascript/

alternatively, there seems to be lots of APIs or Node JS that can manage this. This will allow you to rename the file after it's been downloaded and is now a local file.

  • Related