Javascript重命名文件下载

Javascript rename file on download

本文关键字:文件下载 重命名 Javascript      更新时间:2023-09-26

我希望能够下载一个web文件,但是当下载对话框打开时,文件名被重命名。

示例:File: http://<server>/<site>/test.txt

,当我点击下载文件时,下载对话框打开,文件名:test001.txt

我怎样才能做到呢?

正如InviS所建议的,现在链接上有一个download属性。

的例子:

<a href="http://server/site/test.txt" download="test001.txt">Download Your File</a>

    规范
  • 文章
  • 浏览器支持(Chrome、FF、Opera、Android浏览器)

您可以在链接标签<a href="http://server/site/test.txt" download="test001.txt">Download Your File</a>上使用下载属性

但是,当在服务器响应上设置内容处理头时,它将忽略下载属性,并且文件名将被设置为内容处理响应头

中的文件名。

您可以使用axios或任何其他获取方法来完成此操作:

const downloadAs = (url, name) => {
  Axios.get(url, {
    headers: {
      "Content-Type": "application/octet-stream"
    },
    responseType: "blob"
  })
    .then(response => {
      const a = document.createElement("a");
      const url = window.URL.createObjectURL(response.data);
      a.href = url;
      a.download = name;
      a.click();
    })
    .catch(err => {
      console.log("error", err);
    });
};

用法:

downloadAs('filedownloadlink', 'newfilename');

注意:如果你的文件很大,在整个文件被下载之前,它会看起来像什么都不做,所以一定要向用户显示一些消息或一些指示,让他们知道它正在做一些事情

这个效果是通过发送一个额外的头来实现的。例如,您可以使用PHP来实现:

url可以使用.htaccess重写,(内部)将请求重定向到PHP文件。我将展示一个简单的硬编码示例,说明如何设置标题:

<?php
    header('Content-type: text/plain');
    header('Content-Disposition: attachment; filename="test001.txt"');
    readfile('files/test.txt');
     //assuming that the files are stored in a directory, not in a database
?>

使用链接的download属性。但它只适用于Chrome浏览器:)

你不能在Javascript中这样做。"保存到"对话框是由浏览器打开的,你不能通过JS访问它,它是来自操作系统的标准对话框。

在用户点击下载链接之前,服务器必须为文件提供所需的名称。

你想重命名下载文件的原因是什么?

如果您想要返回连续类型的文件名,则必须编写一个脚本来跟踪该文件名并将该文件返回给用户。一种方法是使用纯PHP,或者更高级的方法,如果一次有几个文件,可能是在PHP中调用cURL,这样它可以生成几个不同的文件。我猜这就是你想要做的,但是你不能在保存框上动态地改变文件名在这种意义上,你返回savename.txt文件名

您可以使用Fetch API下载文件,将获取响应转换为Blob,从Blob创建Blob URL,然后使用带有下载属性的锚(使用所需的名称)从Blob URL下载文件。

        <Link
            onClick={async() => {
                const url = `https://external-website.com/${file.s3Key}`;
                const downloadedFile = await fetch(url).then(response => {
                    if (response.ok) {
                        return response.blob();
                    }
                    else {
                        errorToast('It was not possible to download the file');
                        return undefined;
                    }
                });
                if (downloadedFile) {
                    const a = document.createElement('a');
                    const downloadUrl = window.URL.createObjectURL(downloadedFile as any);
                    a.href = downloadUrl;
                    a.download = file.filename; // use the name you want
                    a.click();
                }
            }}
            sx={{
                textDecoration: 'none',
                fontSize: 16,
                cursor: 'pointer'
            }}
        >
            Download
        </Link>