我正在制作一个包含用户个人资料的网站,他们可以在那里上传他们的头像。我需要从用户那里获取照片并将其存储在用户数据库中。首先从用户那里得到一张图片并将信息发送到服务器:
saveButton.onclick = (() => {
const file = photoInput.files[0];
const reader = new FileReader();
reader.readAsArrayBuffer(file);
reader.onload = (async () => {
const bytes = reader.result;
const description = descriptionInput.value;
const data = JSON.stringify({
photo: bytes,
description
});
await fetch("[username]/changedata", {
method: "PUT",
headers: {
"Content-Type": "application/json"
},
body: data
});
window.location.reload();
});
});
然后尝试将此图像存储在用户数据库中:
app.MapPut("{username}/changedata", async (string username, HttpContext context) =>
{
var data = await context.Request.ReadFromJsonAsync<UserDataChange>();
using var con = new SqlConnection(connection);
await con.OpenAsync();
var command = new SqlCommand();
command.Connection = con;
command.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", data.Photo);
await command.ExecuteNonQueryAsync();
await con.CloseAsync();
});
UserDataChange类:
public class UserDataChange
{
public byte[] Photo { get; set; }
public string Description { get; set; }
}
但是 byte[] 在这种情况下是无效类型。