在前端,我当前正在创建一个FormData对象,该对象包含具有以下属性的数组:“ ProductId” 和“ UserImage” 。为了提供更多上下文,“ UserImage”属性将收到一个Blob(图像)。使用以下2种方法生成Blob:“ imagetoblob” 和“ b64toBlob” 。每当我尝试将FormData发送到服务器端时,我的控制器将冻结大约45秒钟,并返回 Network Error 消息。因此,我无法将FormData的值绑定到我的模型类(产品)。但是,当我从模型类中删除 UserImage变量时,我能够成功发送并绑定formData。
// public IFormFile UserImage { get; set; } // remove
似乎是什么问题?下面是我的代码和我的错误的屏幕截图
更新,我仍在尝试解决此问题。任何帮助将不胜感激!
客户端
// Assuming I have the base64URL values
var base64Image1 = "";
var base64Image2 = "";
const formData = new FormData();
formData.append("Products[0].ProductId", "1");
formData.append("Products[0].UserImage", imagetoblob(base64Image1));
formData.append("Products[1].ProductId", "1");
formData.append("Products[1].UserImage", imagetoblob(base64Image2));
function b64toBlob(b64Data, contentType, sliceSize) {
contentType = contentType || "";
sliceSize = sliceSize || 512;
var byteCharacters = atob(b64Data);
var byteArrays = [];
for (
var offset = 0;
offset < byteCharacters.length;
offset += sliceSize
) {
var slice = byteCharacters.slice(offset, offset + sliceSize);
var byteNumbers = new Array(slice.length);
for (var i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
var blob = new Blob(byteArrays, { type: contentType });
return blob;
}
function imagetoblob(base64Image) {
// Split the base64 string in data and contentType
var block = base64Image.split(";");
// Get the content type of the image
var contentType = block[0].split(":")[1]; // In this case "image/gif"
// get the real base64 content of the file
var realData = block[1].split(",")[1]; // In this case "R0lGODlhPQBEAPeoAJosM...."
// Convert it to a blob to upload
return b64toBlob(realData, contentType);
}
服务器端(控制器)
[HttpPost("verifyCart")]
public async Task<IActionResult> verifyCart([FromForm] List<Product> products)
{
}
服务器端(模型类)
public class Product
{
public int ProductId { get; set; }
public IFormFile UserImage { get; set; }
}
答案 0 :(得分:0)
我认为您的主要问题是如何将文件追加到formData以及模型中使用的类型。
如果我是你,这就是我要做的事情:
formData.append("UserImage", imagetoblob(base64Image1));
formData.append("UserImage", imagetoblob(base64Image2));
您可以在此处将多个文件附加到同一“ UserImage”键。
public class Product
{
public int ProductId { get; set; }
public List<IFormFile> UserImage { get; set; }
}
在模型中,使用列表作为数据类型。 这应该适用于单个文件或多个文件上载。