下载刚刚用 html 输入文件上传的文件

phe*_*epa 3 html javascript file

我有经典的 HTML 文件输入类型

<input type="file" id="xxx" name="xxx" />
Run Code Online (Sandbox Code Playgroud)

我希望用户可以选择下载回他刚刚上传的文件。

我尝试使用 javascript 通过文件路径下载,但 chrome 似乎有一些安全功能,可以用“fakepath”替换真实路径

C:\fakepath\xxx.pdf

知道如何下载上传的文件(只是客户端,尚未提交表单)?

Tim*_*imo 6

您可以使用URL.createObjectURL()创建允许用户下载文件的链接。

const input = document.getElementById('upload');
const link = document.getElementById('link');
let objectURL;

input.addEventListener('change', function () {
  if (objectURL) {
    // revoke the old object url to avoid using more memory than needed
    URL.revokeObjectURL(objectURL);  
  }

  const file = this.files[0];
  objectURL = URL.createObjectURL(file);

  link.download = file.name; // this name is used when the user downloads the file
  link.href = objectURL;
});
Run Code Online (Sandbox Code Playgroud)
<input type="file" id="upload" />
<a id="link" download>link to your file (upload a file first)</a>
Run Code Online (Sandbox Code Playgroud)

请注意该片段:浏览器可能会阻止以这种方式进行多次下载。