ASP.NET MVC从字节[]返回文件
本文关键字:返回 文件 字节 NET MVC ASP | 更新日期: 2023-09-27 18:25:25
我想下载文件,这是以前的文件,但以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;
}
//我的产品控制器
public ActionResult JobOfferReplies(int jobOfferId)
{
List<ApplyForm> allReplies = dbConnection.ApplyForms.Where(x => x.TargetOfferId == jobOfferId).ToList();
return View(allReplies);
}
//JobOfferReplies查看
@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>
//我的产品控制器
public FileContentResult DownloadCv(byte[] file, string contentType)
{
return new FileContentResult(file, contentType);
}
在我们的代码中,我们如下所示:
entityItem= new byte[file.ContentLength];
file.InputStream.Read(entityItem, 0, file.ContentLength);
file.InputStream.Close();
并返回
return File(entityItem, "application/octet-stream");