从服务器下载后无法打开文件

时间:2019-05-15 08:33:06

标签: asp.net-mvc

从服务器(pdf,jpg,..)成功下载文件后,我无法在计算机中打开该文件。 它说:“我们似乎不支持此文件格式。”文件在服务器上存储并可读。 想知道我的下载功能中是否缺少某些内容:

[HttpGet]
public ActionResult Download(Guid? attachmentId)
{
    var visitAttachment = _visitAttachmentService.FindOne(x => x.Id == attachmentId);
    try
    {
        var serverPath = Server.MapPath(visitAttachment.Path);
        byte[] fileBytes = System.IO.File.ReadAllBytes(serverPath);
        return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, visitAttachment.AttachmentName);
    }
    catch
    {
        return File(Encoding.UTF8.GetBytes(""), System.Net.Mime.MediaTypeNames.Application.Octet, visitAttachment.AttachmentName);
    }
}

2 个答案:

答案 0 :(得分:0)

似乎文件下载不正确,请尝试此操作,可能有帮助,祝您好运

  FileDownload(yourfilepath ,yourfilenamewithFormat)
    {
        string filename = yourfilenamewithFormat;
        byte[] file_Bytes = System.IO.File.ReadAllBytes(yourfilepath);
        return File(file_Bytes, System.Net.Mime.MediaTypeNames.Application.Octet, filename);
    }

答案 1 :(得分:0)

我认为您可能缺少文件扩展名。在这种情况下,您可以使用Path.GetExtension(serverPath)

已编辑

尝试使用FileResult代替ActionResult

[HttpGet]
public FileResult Download(Guid? attachmentId)
{
    var visitAttachment = _visitAttachmentService.FindOne(x => x.Id == attachmentId);
    try
    {
        var serverPath = Server.MapPath(visitAttachment.Path);
        byte[] fileBytes = System.IO.File.ReadAllBytes(serverPath);
        return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, visitAttachment.AttachmentName);

    }
    catch
    {
        return File(Encoding.UTF8.GetBytes(""), System.Net.Mime.MediaTypeNames.Application.Octet, visitAttachment.AttachmentName);
    }

}