簡體   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