繁体   English   中英

更改客户端上传文件的名称

[英]Change name of uploaded file on client

我有以下内容。

<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"

您可以通过File API 我们还可以使用Blob API 与Microsoft edge兼容

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

这是一个完整的例子 - 见评论:

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
    });
});

您无法使用标准form提交重命名该文件。 要上载的文件的name是只读的。 要做到这一点,你必须在服务器端做。 (文件上传的设计者似乎没有考虑过这个重命名的上传用例,或者认为它不需要由API解决。)

但是,您可以防止默认的表单提交,而是通过AJAX编程方式提交,这确实让你重命名文件; 看到man tou的回答

如果您无法在服务器端工作,则必须在上载或下载后重命名该文件。 您可以决定如何为用户显示名称。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM