簡體   English   中英

C#中如何將javascript的base64字符串轉成文件

[英]In C#, how to convert the javascript's base64 string into a file

在angular中,我正在制作這樣的表格,

form = this.fb.group({
product_Id: [0]
product_Name: [''],
product_Image: ['']
})

現在我想在 base64 字符串中傳遞產品圖像。 所以我在下面使用它進行了轉換,

fileSelected(files: FileList)
{
let file = <File>files[0]

let reader = new FileReader()
reader.readAsDataURL(file)
reader.onloadend = () => {
this.form.get('product_Image').setValue(reader.result)
}
}

在 asp.net 核心端,我實現了以下邏輯,

var path = Directory.GetCurrentDirectory() + "wwwroot\\Product\\test.jpg";

await File.WriteAllBytesAsync(path, Convert.FromBase64String(vm.Product_Image));

現在 asp.net 核心給我錯誤:“給定的格式不是有效的 base 64 字符串”

PS:我也有 reader.readAsBinaryString(file) 但錯誤是一樣的。

錯誤:輸入不是有效的 Base-64 字符串,因為它包含非 base 64 字符、兩個以上的填充字符或填充字符中的非法字符。

我不知道有什么問題?

根據readAsDataURLMDN 頁面,您必須在解碼前刪除 URI 部分。 我引用:

注意:如果不首先刪除 Base64 編碼數據之前的數據 URL 聲明,則無法將 blob 的結果直接解碼為 Base64。 要僅檢索 Base64 編碼的字符串,請首先從結果中刪除data:*/*;base64,

嘗試從之前的 vm.Product_Image 字符串中刪除“data:image/jpeg;base64”

await File.WriteAllBytesAsync(path, Convert.FromBase64String(vm.Product_Image));

示例 base 64string 如下

/9j/4AAQSkZJRgABAQEASABIAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKC...

暫無
暫無

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

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