I want to download file, that was earlier but into database as byte[] (varbinary(max) in sql), but when I try to call DownloadCv method I get exception: "Input Data is not valid base-64 string."
Could You help me find my mistake or show another way to download file please? Cheers.
Here is what I currently have:
public class ApplyForm
{
/*Some other properties
...
*/
public int FileSize { get; set; }
public string FileName { get; set; }
public byte[] FileData { get; set; }
public string ContentType { get; set; }
}
//Apply View
@model SourceTreeITMatchmaking.Core.Model.ApplyForm
@{
ViewBag.Title = "Apply";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div>
<!-- Some properties to bind to ApplyForm are not shown here to avoid misunderstandings-->
<input class="form-control col-md-2" type="file" name="file" />
<input class="form-control col-md-2" type="submit" value="Upload" />
<input type="hidden" name="jobOfferId" value="@Model.TargetOfferId" />
</div>
//Apply action after posting form
[HttpPost]
public ActionResult Apply(HttpPostedFileBase file, ApplyForm applyForm, int jobOfferId)
{
if (file.ContentLength > 0)
{
applyForm.FileName = file.FileName;
applyForm.FileSize = file.ContentLength;
applyForm.FileData = GetFileBytes(file);
applyForm.ContentType = file.ContentType;
dbConnection.ApplyForms.Add(applyForm);
dbConnection.SaveChanges();
return RedirectToAction("JobList", "JobOffer");
}
}
//Method to get byte[] from HttpPostedFileBase
private static byte[] GetFileBytes(HttpPostedFileBase file)
{
var streamLength = file.InputStream.Length;
var imageBytes = new byte[streamLength];
file.InputStream.Read(imageBytes, 0, imageBytes.Length);
return imageBytes;
}
//MyOffersController
public ActionResult JobOfferReplies(int jobOfferId)
{
List<ApplyForm> allReplies = dbConnection.ApplyForms.Where(x => x.TargetOfferId == jobOfferId).ToList();
return View(allReplies);
}
//JobOfferReplies View
@model List<SourceTreeITMatchmaking.Core.Model.ApplyForm>
@{
ViewBag.Title = "JobOfferReplies";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div>
@Html.ActionLink("Download CV", "DownloadCv", "MyOffers", new {file = applyForm.FileData, contentType = applyForm.ContentType }, new { @class = "btn btn-default pull-left" })
<div>
//MyOffersController
public FileContentResult DownloadCv(byte[] file, string contentType)
{
return new FileContentResult(file, contentType);
}