[英]Unable to upload Image to database due to Base64 error
我正在關注有關如何將圖像上傳到數據庫然后進行檢索的教程。 我的WCF服務運行正常,它具有將數據插入數據庫的功能,如下所示:
public bool CreateTeam(string userId, string teamId, string name, string coach, byte[] photo)
{
string query = "INSERT INTO t" + userId + "(Id, Name, Coach, Photo) VALUES (@id, @name, @coach, @photo)";
try
{
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["TeamsConnectionString"].ConnectionString);
SqlCommand command = new SqlCommand(query, connection);
connection.Open();
command.Parameters.AddWithValue("@id", teamId);
command.Parameters.AddWithValue("@name", name);
command.Parameters.AddWithValue("@coach", coach);
command.Parameters.AddWithValue("@photo", photo);
command.ExecuteNonQuery();
connection.Close();
return true;
}
catch (Exception ex)
{
Console.WriteLine("" + ex.Message);
return false;
}
}
在我的控制器中,我有一個對WCF服務的引用和一個HttpPostedFileBase
來獲取上傳的文件,如下所示:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Team team)
{
if (ModelState.IsValid)
{
HttpPostedFileBase photo = Request.Files["Photo"];
TeamsService.ServiceClient client = new TeamsService.ServiceClient();
client.Open();
if (client.CreateTeam(Session["DynamixSessionId"].ToString(), team.Id, team.Name, team.Coach, ConvertToBytes(photo)))
{
client.Close();
return RedirectToAction("Index", "Teams");
}
else
{
return View();
}
}
return View();
}
下面概述了ConvertToBytes
函數:
public byte[] ConvertToBytes(HttpPostedFileBase file)
{
byte[] fileBytes = null;
BinaryReader reader = new BinaryReader(file.InputStream);
fileBytes = reader.ReadBytes((int)file.ContentLength);
return fileBytes;
}
我的Team
模型是這樣的:
[Key]
[Required(AllowEmptyStrings = false, ErrorMessage = "This cannot be empty")]
public string Id { get; set; }
[Required(AllowEmptyStrings = false, ErrorMessage = "This cannot be empty")]
public string Name { get; set; }
[Required(AllowEmptyStrings = false, ErrorMessage = "This cannot be empty")]
public string Coach { get; set; }
public byte[] Photo { get; set; }
public HttpPostedFileBase File { get; set; }
在我的視圖中,我有一個帶有enctype
屬性的表單,如下所示:
@using (Html.BeginForm("Create", "Teams", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Id, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Id, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Id, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Coach, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Coach, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Coach, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<input type="file" name="Photo" id="Photo" />
</div>
</div>
}
當我單擊提交按鈕時,其他字段將正確插入,並且可以從我的SQL Server數據庫中看到它們。 一旦添加我的Photo
域(類型為varbinary
),就會出現以下錯誤:
輸入內容不是有效的Base-64字符串,因為它包含非Base 64字符,兩個以上的填充字符或填充字符中的非法字符。
為什么會出現此錯誤? 關於如何解決錯誤的任何建議?
我的建議是您應該指定參數類型。 commandd.Parameters.Add("@photo", SqlDbType.VarBinary, LengthOfFieldOnTheServerSide).Value = photo;
這個建議是基於我之前對SQL查詢的“打架”。 對我來說,它正在使用system.byte []
代替參數byte []
的實際值來創建查詢。
抱歉打錯我在手機上使用StackExchange應用程序
為什么您的文件上傳控件使用模型中“ Photo
字段的ID? “ Photo
字段必須為HttpPostedFileBase
類型,以便正確上傳圖像並避免Base64
錯誤。 我建議您進行以下更改:
在模型中 ,添加以下內容:
public HttpPostedFileBase UploadedPhoto { get; set; }
在您的視圖中 ,添加以下內容:
<input type="file" name="UploadedPhoto" id="UploadedPhoto" />
在您的控制器中 ,添加以下內容:
HttpPostedFileBase photo = Request.Files["UploadedPhoto"]; TeamsService.ServiceClient client = new TeamsService.ServiceClient(); client.Open(); if (client.CreateTeam(Session["DynamixSessionId"].ToString(), team.Id, team.Name, team.Coach, ConvertToBytes(photo))) { client.Close(); return RedirectToAction("Index", "Teams"); } else { return View(); }
那應該解決您的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.