Asp.Net MVC下载varbinary存储在数据库中的文件



我想下载varbinary作为文件存储在数据库中。我可以下载文件,但是从我的应用程序下载的所有文件都无法打开。我注意到我上传的pdf文件大小为200kb。但是当我下载那个文件时,它只返回30字节。

代码如下:

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Upload(Upload model, HttpPostedFileBase uploadFile, String random_number, String rcf_number)
{
var db = new RCFOnlineEntities();
if(uploadFile != null)
{
byte[] bytes;
using (BinaryReader br = new BinaryReader(uploadFile.InputStream))
{
bytes = br.ReadBytes(uploadFile.ContentLength);
}
model.file_base6 = bytes;
model.file_ext = uploadFile.ContentType;
model.file_name = uploadFile.FileName;
model.rcfnumber = rcf_number;
model.randomnumber = random_number;
}

db.Uploads.Add(model);
db.SaveChanges();
return RedirectToAction("Edit", "GetRCFOnline", new { random_number = random_number });
}
[HttpGet]
public FileResult DownLoadFile(int id, String random_number)
{
List<Upload> ObjFiles = GetUploadClasses(random_number);
var FileById = (from FC in ObjFiles
where FC.file_id.Equals(id)
select new { FC.file_name, FC.file_base6 , FC.file_ext}).ToList().FirstOrDefault();


return File(FileById.file_base6, FileById.file_ext, FileById.file_name);
}

你能告诉我代码中的错误在哪里吗?

解决方案1:

使用uploadFile.InputStream.Length而不是还是。ContentLength要正确上传文件大小,即

using (BinaryReader br = new BinaryReader(uploadFile.InputStream))
{
bytes = br.ReadBytes(uploadFile.InputStream.Length);
}

解决方案2:

如果BinaryReader不是一个固定的要求,那么使用下面的解决方案来获取上传文件的字节,即

byte[] bytes = new byte[uploadFile.InputStream.Length];
uploadFile.InputStream.Read(bytes, 0, bytes.Length);

最新更新