簡體   English   中英

使用 blob 將圖像插入 input type="file"

[英]Inserting image into input type="file" using blob

我想在我用 C# MVC Core 編寫的項目中為動物 object 創建一個數據編輯頁面。 我想用存儲在數據庫中的圖像覆蓋 input type="file" 標簽。 這是動物的 class。 照片的屬性是:ImageData、FileName、ContentType。

    public class Animal
    {
        public Guid Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public string Sex { get; set; }
        public int Age { get; set; }
        public string Breed { get; set; }
        public DateTime DateOfPost { get; set; }
        public Guid UserId { get; set; }
        public byte[] ImageData { get; set; }
        public string FileName { get; set; }
        public string ContentType { get; set; }
        public virtual User User { get; set; }
    }
}

我想通過在 javascript 中使用 Blob 來做到這一點。這是我的代碼:

<script>
    const blob = new Blob([@Animal.ImageData], { type: '@Animal.ContentType' });

    const file = new File([blob], '@Animal.FileName', { type: '@Animal.ContentType ' });

document.querySelector('input[type="file"]').files = file;
</script>

我在瀏覽器中收到該錯誤 ( https://i.stack.imgur.com/EhsKT.png ) ( https://i.stack.imgur.com/P8bnj.png )

我試圖用 System.Linq.Enumerable.AsEnumerable 和 System.Linq.Enumerable.ToArray 解決這個問題,但每次我都會遇到同樣的錯誤。 有誰知道如何解決這一問題?

我想用存儲在數據庫中的圖像覆蓋 input type="file" 標簽。

不,你不知道。

退后一步,考慮一下這意味着什么,即使您可以讓它發揮作用。 這意味着每次有人加載此頁面時,您都會向他們發送整個文件而不打算顯示它。 他們根本不使用它。 然后,不對該字段做任何更改,他們發布將整個文件發送回服務器的表單。

為服務器提供它已經擁有的數據,並為客戶端提供他們沒有使用的數據,這是一個很大的網絡流量。

采取不同的方法。 考慮例如這樣的 HTML 結構:

<img src="path_to_your_file">
<button>Delete?</button>
<input type="file" name="myFile">

基本上,您的三個操作具有三個要素:

  1. 顯示當前文件(可選)
  2. 刪除當前文件(不替換)
  3. 用新文件替換當前文件

客戶端必須上傳文件的唯一原因是第三種情況,而不是試圖強制客戶端以某種方式在每種情況下重新下載和重新上傳文件。

很明顯,您可以修改 HTML 以滿足您的需要,根據您的喜好設置樣式,根據您的喜好更改功能等。但總的來說是將這些操作彼此分開,並且只使用您需要的操作利用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM