在MVC3中的Control方法中返回文件

时间:2012-01-10 04:33:29

标签: c# asp.net-mvc-3 model-view-controller c#-4.0

我有一个上传管理器,当用户调用一个特殊的我控制方法时,我希望返回一个文件,如下所示:

www.website.com/upload/getfile/?fileID=100

我该怎么做? 我想知道如何归档文件!


我找到了答案,我在下面写了示例代码:

public FilePathResult GetFile(string Name)
    {
        FilePathResult s = new FilePathResult(@"C:/"+Name, "File");
        Response.Headers.Clear();

        return s;
    }

但是现在有问题。如果我将File用于我的ContentType,则会出现任何问题。因为我不知道。

3 个答案:

答案 0 :(得分:2)

创建一个名为uploadController的控制器,其操作名为getfile,其中包含一个参数。

然后上面的网址可以改为

www.website.com/upload/getfile/100

<强>更新

将操作的返回类型更改为FileResult

要获得完整的答案,请查看我的代码库的一部分:

//Attachment Class
public class Attachment
{
    #region Properties

    public virtual Guid AttachmentId { get; set; }
    public virtual int? ContentLength { get; set; }
    public virtual string ContentType { get; set; }
    public virtual byte[] Contents { get; set; }
    public virtual DateTime? DateAdded { get; set; }
    public virtual string FileName { get; set; }
    public virtual string Title { get; set; }

    #endregion
 }


public class AttachmentController : Controller
{
     IAttachmentService attachmentService;

    public AttachmentController(IAttachmentService attachmentService)
    {
        this.attachmentService = attachmentService;
    }

    public ActionResult Index(Guid id)
    {
        var attachment = this.attachmentService.GetById(id);
        return attachment.IsNull() ? null : this.File(attachment.Contents, attachment.ContentType,attachment.FileName);
    }
}

public class AttachmentModelBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        HttpRequestBase httpRequestBase = controllerContext.RequestContext.HttpContext.Request;
        HttpPostedFileBase @base = httpRequestBase.Files[bindingContext.ModelName];
        var converter = new FileConverter();
        Attachment attachment = converter.Convert(
                new ResolutionContext(
                    new TypeMap(new TypeInfo(typeof(HttpPostedFileWrapper)), new TypeInfo(typeof(Attachment))),
                    @base,
                    typeof(HttpPostedFileWrapper),
                    typeof(Attachment)));
        }
        return attachment;
    }
}

public class MvcApplication : HttpApplication
{
    protected void Application_Start()
    {
        ModelBinders.Binders[typeof(Attachment)] = new AttachmentModelBinder();
    }
}

答案 1 :(得分:1)

答案 2 :(得分:1)

你能试试吗

public void getFile(fileId id) 
{
    FileInfo fileInfo = GetFileInfo(id); //Your function, which returns File Info for the Id
    Response.ClearContent();
    Response.ClearHeaders();
    Response.AddHeader("Content-Length", fileInfo.Length.ToString());
    Response.TransmitFile(fileInfo.FullName);
    Response.ContentType = "CONTENT TYPE";
    Response.Flush();
}

我用它来从服务器获取MP3文件。

希望这有帮助。