【发布时间】:2018-11-30 16:06:31
【问题描述】:
如何从 db 而不是从某个路径下载文件? 我正在以这种方式上传文件:
[HttpPost, ActionName("CandidateCreate")]
[ValidateAntiForgeryToken]
public IActionResult CandidateCreatePost([Bind("Name,Number,Profile,CV,CVID")] Candidate candidate, IFormFile CV)
{
if (ModelState.IsValid)
{
if (CV != null)
{
if (CV.Length > 0)
{
byte[] p1 = null;
using (var fs1 = CV.OpenReadStream())
using (var ms1 = new MemoryStream())
{
fs1.CopyTo(ms1);
p1 = ms1.ToArray();
}
candidate.CVNAME = CV.FileName;
candidate.CV = p1;
}
}
using (var applicationContext = new ApplicationContext())
{
candidateRepository.Add(candidate);
candidateRepository.SaveChanges();
return RedirectToAction("Candidate");
}
}
return View();
}
我能找到的关于下载的一切都只有路径
**EDIT1 **
我试过这个:
public async Task<IActionResult> Download(string filename, Candidate candidate, IFormFile CV)
{
filename = candidate.Name;
if (filename == null)
return Content("filename not present");
var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", filename);
var memory = new MemoryStream();
using (var stream = new FileStream(path, FileMode.Open))
{
await stream.CopyToAsync(memory);
}
memory.Position = 0;
return File(memory, GetContentType(path), Path.GetFileName(path));
}
private string GetContentType(string path)
{
var types = GetMimeTypes();
var ext = Path.GetExtension(path).ToLowerInvariant();
return types[ext];
}
private Dictionary<string, string> GetMimeTypes()
{
return new Dictionary<string, string>
{
{".pdf", "application/pdf"},
{".doc", "application/vnd.ms-word"},
{".docx", "application/vnd.ms-word"}
};
}
我收到一个错误,因为这是使用路径... 我需要一些没有路径属性的东西(我认为)
【问题讨论】:
-
控制器上有一个
File方法,它将接受stream、byte[]或path将文件下载到浏览器 -
而不是actionResult? @SimplyGed
-
没有。 IActionResult 很好。您需要拨打
File(...)而不是View()。例如return File(p1, "application/octetstream", CV.Filename) -
查看this question 的答案示例
标签: asp.net asp.net-core