我想下载文件,这是早期但是作为byte [](sql中的varbinary(max))进入数据库,但是当我尝试调用DownloadCv方法时,我得到异常: “输入数据不是有效的base-64字符串。”
你能帮我找到我的错误或者显示另一种下载文件的方法吗? 欢呼声。
以下是我目前的情况:
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; }
}
//应用视图
@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>
//发布表单后应用操作
[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");
}
}
//从HttpPostedFileBase获取byte []的方法
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);
}
答案 0 :(得分:1)
在我们的代码中,我们按如下方式执行:
entityItem= new byte[file.ContentLength];
file.InputStream.Read(entityItem, 0, file.ContentLength);
file.InputStream.Close();
并返回
return File(entityItem, "application/octet-stream");