JS 通过 URL 下载文件并重命名(两种方式)

文章介绍了如何使用JavaScript通过HTML的a标签以及Blob数据类型来实现从URL下载文件并进行重命名的功能。第一种方法是直接设置a标签的href和download属性,而第二种方法涉及异步获取Blob对象然后利用saveAs函数保存文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

JS 通过 URL 下载文件并重命名(两种方式)

一、a 标签简单设置 href 方式

// 下载文件
function downloadFile() {
  const link = document.createElement('a');
  link.style.display = 'none';
  // 设置下载地址
  link.setAttribute('href', file.sourceUrl);
  // 设置文件名
  link.setAttribute('download', file.fileName);
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
}

二、a 标签使用 blob 数据类型方式

async function download(downloadUrl: string, downloadFileName: string ) {
  const blob = await getBlob(downloadUrl);
  saveAs(blob, downloadFileName );
}

function getBlob(url: string) {
  return new Promise<Blob>((resolve, reject) => {
    const xhr = new XMLHttpRequest();

    xhr.open('GET', url, true);
    xhr.responseType = 'blob';
    xhr.onload = () => {
      if (xhr.status === 200) {
        resolve(xhr.response);
      } else {
        reject(new Error(`Request failed with status ${xhr.status}`));
      }
    };
    xhr.onerror = () => {
      reject(new Error('Request failed'));
    };

    xhr.send();
  });
}

function saveAs(blob: Blob, filename: string) {
  const link = document.createElement('a');
  const body = document.body;

  link.href = window.URL.createObjectURL(blob);
  link.download = filename;

  // hide the link
  link.style.display = 'none';
  body.appendChild(link);

  link.click();
  body.removeChild(link);

  window.URL.revokeObjectURL(link.href);
}

### Java 实现文件下载并重命名 在Java中,可以通过组合使用`HttpURLConnection`类进行文件下载以及`File`类中的`renameTo()`方法来进行文件命名。下面是一个完整的例子,展示了如何从网络位置下载文件至本地存储,将其命名为自定义名称。 #### 下载文件部分 为了完成这一过程,程序首先创建一个URL对象指向目标资源的位置;接着通过打开HTTP连接读取数据流;最后将接收到的数据写入到一个新的文件实例当中保存下来。 ```java import java.io.*; import java.net.HttpURLConnection; import java.net.URL; public class DownloadAndRename { private static final String DOWNLOAD_URL = "http://example.com/file.zip"; private static final String TEMP_FILE_NAME = "tempDownloadedFile.zip"; public static void downloadFile() throws IOException { URL url = new URL(DOWNLOAD_URL); HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); int responseCode = httpConn.getResponseCode(); // Check HTTP response code for success before initiating transfer. if (responseCode == HttpURLConnection.HTTP_OK) { InputStream inputStream = httpConn.getInputStream(); FileOutputStream outputStream = null; try { outputStream = new FileOutputStream(TEMP_FILE_NAME); byte[] buffer = new byte[4096]; int bytesRead = -1; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } outputStream.close(); inputStream.close(); System.out.println("File downloaded"); } catch (IOException e) { throw new RuntimeException(e); } finally { if (outputStream != null){ try{ outputStream.close(); }catch(IOException ex){} } httpConn.disconnect(); } } else { System.out.println("No file to download. Server replied HTTP code: " + responseCode); } } } ``` #### 文件命名部分 一旦文件成功下载到了临时位置,则可以根据需求调用`File.renameTo()`函数给它赋予新名字: ```java public static boolean renameFile(){ File tempFile = new File(TEMP_FILE_NAME); File renamedFile = new File("desiredFileName.zip"); return tempFile.renameTo(renamedFile); } // 调用上述两个功能的方法如下所示: try { DownloadAndRename.downloadFile(); // Step one: Download the file first. if (DownloadAndRename.renameFile()) { // Then attempt renaming it after successful downloading. System.out.println("Renaming succeeded."); } else { System.out.println("Renaming failed."); } } catch (Exception e) { e.printStackTrace(); } ``` 需要注意的是,在实际应用环境中应当考虑异常处理机制以应对可能出现的各种错误情况,比如网络中断或是权限不足等问题[^1]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值