如何在ASP.NET网页获取用户图片并存储到SQL Server数据库?
问题分析
你的核心问题是JSON无法直接序列化ArrayBuffer:前端将ArrayBuffer类型的图片数据放入JSON.stringify后,会被转换为空对象{},导致后端无法正确反序列化为byte[]类型,最终存储失败。
解决方案
提供两种可行的修改方案,按需选择:
方案1:Base64字符串传输(适合小体积图片)
前端修改
将图片转为Base64字符串(JSON可正常序列化字符串),去掉Data URL前缀后发送:
saveButton.onclick = (() => { const file = photoInput.files[0]; const reader = new FileReader(); reader.readAsDataURL(file); reader.onload = async () => { // 提取Base64部分,移除"data:image/xxx;base64,"前缀 const base64Photo = reader.result.split(',')[1]; const description = descriptionInput.value; const data = JSON.stringify({ photo: base64Photo, description }); await fetch(`[username]/changedata`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: data }); window.location.reload(); }; });
后端修改
- 更新
UserDataChange类,将Photo改为string类型接收Base64:
public class UserDataChange { public string Photo { get; set; } public string Description { get; set; } }
- 在接口中把Base64字符串转回
byte[]再存入数据库:
app.MapPut("{username}/changedata", async (string username, HttpContext context) => { var data = await context.Request.ReadFromJsonAsync<UserDataChange>(); // 将Base64字符串转换为byte数组 byte[] photoBytes = Convert.FromBase64String(data.Photo); using var con = new SqlConnection(connection); await con.OpenAsync(); var command = new SqlCommand { Connection = con, CommandText = @"UPDATE [users] SET description=@description, picture=@picture WHERE username=@username" }; command.Parameters.AddWithValue("username", username); command.Parameters.AddWithValue("description", data.Description); command.Parameters.AddWithValue("picture", photoBytes); await command.ExecuteNonQueryAsync(); // using块会自动释放连接,无需手动调用CloseAsync });
方案2:FormData上传(适合大体积图片,更高效)
用FormData直接传输文件,避免Base64的体积开销,这是文件上传的标准方案:
前端修改
saveButton.onclick = async () => { const file = photoInput.files[0]; const description = descriptionInput.value; const formData = new FormData(); formData.append("photo", file); formData.append("description", description); await fetch(`[username]/changedata`, { method: "PUT", body: formData // 无需手动设置Content-Type,浏览器会自动添加正确的multipart/form-data头 }); window.location.reload(); };
后端修改
直接读取FormData中的文件和描述,转成byte[]存储:
app.MapPut("{username}/changedata", async (string username, HttpContext context) => { var form = await context.Request.ReadFormAsync(); var description = form["description"]; var photoFile = form.Files["photo"]; // 将文件流转换为byte数组 byte[] photoBytes; using (var memoryStream = new MemoryStream()) { await photoFile.CopyToAsync(memoryStream); photoBytes = memoryStream.ToArray(); } using var con = new SqlConnection(connection); await con.OpenAsync(); var command = new SqlCommand { Connection = con, CommandText = @"UPDATE [users] SET description=@description, picture=@picture WHERE username=@username" }; command.Parameters.AddWithValue("username", username); command.Parameters.AddWithValue("description", description); command.Parameters.AddWithValue("picture", photoBytes); await command.ExecuteNonQueryAsync(); });
内容的提问来源于stack exchange,提问作者vladlen32230
相关产品推荐
相关产品推荐

