在ASP.NET MVC中上传文件 [英] uploading files in ASP.NET MVC

查看:131
本文介绍了在ASP.NET MVC中上传文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我选择一个文件,并提交文件进行上传,我不能让我的模型文件路径的值。在控制它显示为。我究竟做错了什么?

查看

 <形式方法=邮报行动=/帐号/个人资料ENCTYPE =的multipart / form-data的>
    <标签>将照片:LT; /标签>
    <输入类型=文件名称=文件路径ID =文件/>
    <输入类型=提交值=提交/>
< /形式GT;
 

控制器

 公众的ActionResult资料(ProfileModel模型的FormCollection形式)
{
    字符串路径= Convert.ToString(model.FilePath);
    返回查看();
}
 

型号

 公共HttpPostedFileBase文件路径
{
    得到
    {
        返回_filePath;
    }
    组
    {
        _filePath =价值;
    }
}

公共BOOL UploadFile()
{
    如果(文件路径!= NULL)
    {
        VAR文件名= Path.GetFileName(FilePath.FileName);
        FilePath.SaveAs(@C:\+文件名);
        返回true;
    }
    返回false;
}
 

解决方案

我不认为模型绑定与 HttpPostedFileBase ...

工程

这应该工作,如果你把它从你的视图模型,做这样的:

 公众的ActionResult资料(HttpPostedFileBase文件路径)
{
    字符串路径= Convert.ToString(文件路径);
    返回查看();
}
 

HTHS,
查尔斯

诗。这篇文章可能有助于解释的事情:<一href="http://stackoverflow.com/questions/960687/asp-net-mvc-posted-file-model-binding-when-parameter-is-model">ASP.NET MVC发布文件模型绑定时参数型号

When I select a file and submit the file for upload, I can't get the value of the File path in my Model. In the Controller it shows as null. What am I doing wrong?

View

<form method="post" action="/Account/Profile" enctype="multipart/form-data">
    <label>Load photo: </label>
    <input type="file" name="filePath" id="file" />
    <input type="submit" value="submit" />
</form>

Controller

public ActionResult Profile(ProfileModel model, FormCollection form)
{
    string path = Convert.ToString(model.FilePath);
    return View();
}

Model

public HttpPostedFileBase FilePath
{
    get
    {
        return _filePath;
    }
    set
    {
        _filePath = value;
    }
}

public bool UploadFile()
{
    if (FilePath != null)
    {
        var filename = Path.GetFileName(FilePath.FileName);
        FilePath.SaveAs(@"C:\" + filename);
        return true;
    }
    return false;
}

解决方案

I don't think model binding works with HttpPostedFileBase...

It should work if you take it out of your ViewModel and do it like this:

public ActionResult Profile(HttpPostedFileBase filePath)
{
    string path = Convert.ToString(filePath);
    return View();
}

HTHs,
Charles

Ps. This post could help explain things: ASP.NET MVC posted file model binding when parameter is Model

这篇关于在ASP.NET MVC中上传文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆