【问题标题】:Change name of uploaded file on client在客户端更改上传文件的名称
【发布时间】:2018-08-10 08:32:18
【问题描述】:

我有以下。

<form method="post" action="/send" enctype="multipart/form-data">
    <input type="file" name="filename" id="AttachFile">
</form>

我想更改用户上传的文件的名称。

如果用户选择“Document.docx”,我想将其更改为“Bank - Document.docx”。

我仍然想读取用户选择的文件,而不是其他文件,只是在发送到服务器时使用不同的名称。

我在不允许控制服务器端的应用程序范围内工作,因此理想情况下我需要在客户端上执行此操作。此外,我需要它在 form 的范围内工作。

我尝试了以下变体但没有成功:

document.getElementById("AttachFile").name = "test.txt"
document.getElementById("AttachFile").files = "test.txt"
document.getElementById("AttachFile").value ="test.txt"

【问题讨论】:

  • 所以您想在上传前将“picOfMyCat.jpg”更改为“/banking/secretpasswords.dat”?祝你好运;)
  • @mplungjan - 我认为目标是读取用户识别的文件,而不是其他文件,只是在发送到服务器时使用不同的名称。所以发送的文件仍然是picOfMyCat.jpg,只是名称为secretpasswords.dat。 :-)
  • @mplungjan,别担心我值得信赖!
  • @T.J.Crowder,是的,这就是我的目标。
  • @T.J.Crowder 我知道。我在开玩笑。但是浏览器不允许该用例

标签: javascript html


【解决方案1】:

您可以通过File API 进行操作。我们也可以使用Blob APIcompatible with Microsoft edge

var file = document.getElementById("AttachFile").files[0];
var newFile = new File([file], "Bank - Document.docx", {
  type: file.type,
});

这是一个完整的例子——见 cmets:

HTML:

<input type="file" id="AttachFile">
<input type="button" id="BtnSend" value="Send">

JavaScript:

document.getElementById("BtnSend").addEventListener("click", function() {
    // Get the file the user picked
    var files = document.getElementById("AttachFile").files;
    if (!files.length) {
        return;
    }
    var file = files[0];
    // Create a new one with the data but a new name
    var newFile = new File([file], "Bank - Document.docx", {
      type: file.type,
    });
    // Build the FormData to send
    var data = new FormData();
    data.set("AttachFile", newFile);
    // Send it
    fetch("/some/url", {
        method: "POST",
        body: data
    })
    .then(response => {
        if (!response.ok) {
            throw new Error("HTTP error " + response.status);
        }
        return response.text(); // or response.json() or whatever
    })
    .then(response => {
        // Do something with the response
    })
    .catch(error => {
        // Do something with the error
    });
});

【讨论】:

  • ...然后通过fetch 使用FormData 发送该文件。优秀的。我知道有些事情困扰着我。
  • Edge 支持 fetch API 吗?
  • 你认为这会在form 的范围内工作吗?我已经更新了我的问题 - 抱歉应该在之前提出。
  • @anjanesh - Yes, since v14(以及自 v12 以来的 FormData)。要支持 Edge v12 和 v13,您可以使用 XMLHttpRequest
【解决方案2】:

您不能使用标准的form 提交来重命名文件。正在上传的文件的name 是只读的。为此,您必须在服务器端进行。 (文件上传的设计者似乎没有考虑过这种上传时重命名用例,或者认为不需要 API 来解决它。)

但是,您可以阻止默认表单提交,而是通过 ajax 以编程方式提交它,确实允许您重命名文件;见man tou's answer

【讨论】:

  • 能否用js api新建一个文件,命名后填入用户选择文件的内容。
【解决方案3】:

如果您无法在服务器端工作,那么您必须在上传之前或下载之后重命名文件。如何为用户显示名称由您决定。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-14
  • 2012-02-03
  • 2023-04-09
相关资源
最近更新 更多