System.Web.HttpPostedFileWrapper串在保存文件路径名,而不是 [英] System.Web.HttpPostedFileWrapper string is being saved instead of file pathname

查看:1315
本文介绍了System.Web.HttpPostedFileWrapper串在保存文件路径名,而不是的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这用来做工精细,但现在的code未保存的路径名 SitePlan SiteImage 字段。如果我调试一切看起来很好, SitePlan SiteImage 包含路径名上传的文件(例如〜/ UPLOADEDFILES / 20110210104108SiteImage77。 JPG格式)。但是,一旦保存在 SitePlan SiteImage 字段中的字符串值System.Web.HttpPostedFileWrapper。

这个挣扎因为它的保存精美,看着和调试值被保存是如此路径没有错误,所有出现去上班,就数据库没有路,只是这串System.Web.HttpPostedFileWrapper。任何意见大大AP preciated

下面是我的控制器code:

 的[AcceptVerbs(HttpVerbs.Post)
公众的ActionResult SiteLocationEdit(INT ID,收集的FormCollection)
{
    SITELOCATION SITELOCATION = this._siteRepository.GetSite(Convert.ToInt16(集合[SITEID]))SITELOCATION。    如果(Request.Files.Count大于0&放大器;&放大器; Request.Files [SitePlan] CONTENTLENGTH大于0)
    {
        的DeleteFile(siteLocation.SitePlan);
        siteLocation.SitePlan = SAVEFILE(Request.Files [SitePlan],@〜/ UPLOADEDFILES,SitePlan+ siteLocation.SiteId.ToString());
    }    如果(Request.Files.Count大于0&放大器;&放大器; Request.Files [SiteImage] CONTENTLENGTH大于0)
    {
        的DeleteFile(siteLocation.SiteImage);
        siteLocation.SiteImage = SAVEFILE(Request.Files [SiteImage],@〜/ UPLOADEDFILES,SiteImage+ siteLocation.SiteId.ToString());
    }    TryUpdateModel(SITELOCATION);    如果(!ModelState.IsValid)
        返回查看(SITELOCATION);
    this._siteRepository.Save(User.Identity.Name);
    返回RedirectToAction(SiteLocationDetails,新{ID = siteLocation.SiteId});
}

下面是我的看法包含的局部视图(后来在这篇文章中所示)

 <%@页标题=LANGUAGE =C#的MasterPageFile =〜/查看/共享/的Site.Master继承=System.Web.Mvc.ViewPage< Lms.Model.SiteLocation>中%GT;< ASP:内容ID =内容1ContentPlaceHolderID =TitleContent=服务器>
    <%= Html.En code(Model.Site.SiteDescription)%GT;
< / ASP:内容>
< ASP:内容ID =内容2ContentPlaceHolderID =日程地址搜索Maincontent=服务器>
<%= Html.Script(〜/脚本/ jquery.textarea-expander.js)%>    <%= Html.ValidationSummary(位置创建不成功,请更正错误,然后重试\\ n如果此更新中上传的图片,请重新上传。)%>
    <%使用(        Html.BeginForm
        (
            SiteLocationEdit
            现场,
            FormMethod.Post,
           //添加一个编码类型属性
           //所需文件上传
            新{ENCTYPE =的multipart / form-data的}
        )           )
       {%GT;
        <%Html.RenderPartial(SiteTabs,Model.Site); %GT;
        < D​​IV CLASS =清除>
        < / DIV>
        <%Html.RenderPartial(SiteLocationForm模型); %GT;
    <%}%GT;        <脚本类型=文/ JavaScript的>
            / * jQuery的textarea的大小调整插件的使用* /
            $(文件)。就绪(函数(){
                。jQuery的(textarea的[*类扩展=])TextAreaExpander(); //初始化所有扩展文字区域,新的code,约翰小号10/08/2010
            });
        < / SCRIPT>< / ASP:内容>

下面是部分观点:

 <%@控制语言=C#继承=System.Web.Mvc.ViewUserControl< Lms.Model.SiteLocation>中%GT;
<&字段集GT;
    < D​​IV>
        < H3>
            <标签ID =Label2的风格=文本对齐:左>
                <%=站点位置:+ Html.En code(Model.Site.SiteDescription)%GT;< /标签>
        < / H3 GT&;
    < / DIV>
    < D​​IV CLASS =formFields>
        < UL>
            &所述;% - 这是用于识别站点对象模型时返回到控制器更新 - %GT;
            &所述;%= Html.Hidden(SITEID,Model.SiteId)%GT;
            <立GT;
                <标签=纬度>
                    <强>纬度:< / STRONG>< /标签>
                <%= Html.TextBox(纵横)%>
                &所述;%= Html.ValidationMessage(纬度,*)%>
            < /李>
            <立GT;
                <标签=经度>
                    <强>经度:LT; / STRONG>< /标签>
                &所述;%= Html.TextBox(经度)%>
                &所述;%= Html.ValidationMessage(经度,*)%>
            < /李>
            <立GT;
                <标签=位置>
                    <强>位置的地址:LT; / STRONG>< /标签>
                <标签><%= Html.TextArea(位置,Model.Location,新{@class =expand50-200})%GT;< /标签>
                &所述;%= Html.ValidationMessage(位置,*)%>
            < /李>
            <立GT;
                <标签=NearestPost code>
                    <强>最近的帖子code:< / STRONG>< /标签>
                <%= Html.TextBox(NearestPost code)%GT;
                <%= Html.ValidationMessage(NearestPost code,*)%GT;
            < /李>
            <立GT;
                <标签=TimeFromOfficeToTurbine>
                    <强>办公室风电场(时间):其中; / STRONG>< /标签>
                &所述;%= Html.TextBox(TimeFromOfficeToTurbine)%>
                &所述;%= Html.ValidationMessage(TimeFromOfficeToTurbine,*)%>
            < /李>
            <立GT;
                <标签=路线>
                    <强>注释:其中; / STRONG>< /标签>
                <标签><%= Html.TextArea(路线,Model.Directions,新{@class =expand50-200})%GT; < /标签>
                <%= Html.ValidationMessage(路线,*)%GT;
            < /李>            <立GT;
            <&H5 GT;<强>作为图片上传:LT; / STRONG>请只使用JPG,JPEG或GIF格式。
            图像大小应该适合网页显示,大约500x375(宽度x高度)
            < / H5>
            < /李>            <立GT;
                <标签=场地规划>
                    <强>网站规划:其中; / STRONG>< /标签>
                <输入ID =SitePlanNAME =SitePlan类型=文件/>
            < /李>            <立GT;
                <标签=网站的图片>
                    <强>网站图片:LT; / STRONG>< /标签>
                <% - <%= // Html.TextBox(SiteImage,Model.SiteImage)%GT;
            &所述;%// = Html.ValidationMessage(SiteImage,*)%> - %GT;
                <输入ID =SiteImageNAME =SiteImage类型=文件/>
            < /李>
        < / UL>
    < / DIV>
< /字段集>
 < D​​IV CLASS ='示范'>
    <%= Html.ActionLink(<返回名录,索引)%GT;<输入类型=提交值=保存/>
< / DIV>

和这里是在控制器code的保存文件的过程:

 保护字符串SAVEFILE(HttpPostedFileBase文件,路径字符串,字符串名称)
{
    如果(文件= NULL&放大器;!&安培; file.ContentLength大于0)
    {
        如果(路径== NULL)
        {
            抛出新的ArgumentNullException(路径不能为空);
        }        串的fileType = file.FileName.Substring(file.FileName.LastIndexOf(),file.FileName.Length - file.FileName.LastIndexOf()。。);        字符串relpath =的String.Format({0} / {1},路径,prefixFName(名称+的fileType));
        尝试
        {
            file.SaveAs(使用Server.Mappath(relpath));
            返回relpath;
        }
        赶上(HttpException E)
        {
            抛出新ApplicationException的(无法保存上传的文件,E);
        }
    }
    返回null;
}

下面是SiteLocationCreate()这工作,就在编辑一个不:

 的[AcceptVerbs(HttpVerbs.Post)
公众的ActionResult SiteLocationCreate(SITELOCATION SITELOCATION,收集的FormCollection)
{
    // TODO CF:你看这个行。有没有更好的办法做到这一点?我会这样想。
    //它使用一个隐藏字段的形式对象
    站点位置= this._siteRepository.GetSite(Convert.ToInt16(集合[SITEID]));
    site.SiteLocation = SITELOCATION;    如果(Request.Files.Count大于0&放大器;&放大器; Request.Files [SitePlan] CONTENTLENGTH大于0)
    {
        的DeleteFile(siteLocation.SitePlan);
        siteLocation.SitePlan = SAVEFILE(Request.Files [SitePlan],@〜/ UPLOADEDFILES,SitePlan+ siteLocation.SiteId.ToString());
    }    如果(Request.Files.Count大于0&放大器;&放大器; Request.Files [SiteImage] CONTENTLENGTH大于0)
    {
        的DeleteFile(siteLocation.SiteImage);
        siteLocation.SiteImage = SAVEFILE(Request.Files [SiteImage],@〜/ UPLOADEDFILES,SiteImage+ siteLocation.SiteId.ToString());
    }    如果(!ModelState.IsValid)
        返回查看(SITELOCATION);    this._siteRepository.Save(User.Identity.Name);
    返回RedirectToAction(SiteLocationDetails,新{ID = site.SiteId});
}


解决方案

删除TryUpdateModel()线,其工作。但不得不然后通过行对每个领域的更新,即siteLocation.Location =收集[所在地]的指定线;等等等等,由于TryUpdateModel已取出

This used to work fine, but now the code is not saving the pathname to the SitePlan and SiteImage fields. If I debug everything looks fine and SitePlan and SiteImage contain pathnames to the uploaded files (i.e. ~/UploadedFiles/20110210104108SiteImage77.jpg). But once save in the SitePlan and SiteImage fields is the string value "System.Web.HttpPostedFileWrapper".

Struggling with this since its saves fine and watching and debugging the value being saved is the pathname so no error and all appears to work, just the database has no path, just this string "System.Web.HttpPostedFileWrapper". Any comments greatly appreciated

Here is my controller code :

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult SiteLocationEdit(int id, FormCollection collection)
{
    SiteLocation siteLocation = this._siteRepository.GetSite(Convert.ToInt16(collection["SiteId"])).SiteLocation;           

    if (Request.Files.Count > 0 && Request.Files["SitePlan"].ContentLength > 0)
    {
        DeleteFile(siteLocation.SitePlan);
        siteLocation.SitePlan = SaveFile(Request.Files["SitePlan"], @"~/UploadedFiles", "SitePlan" + siteLocation.SiteId.ToString());
    }

    if (Request.Files.Count > 0 && Request.Files["SiteImage"].ContentLength > 0)
    {
        DeleteFile(siteLocation.SiteImage);
        siteLocation.SiteImage = SaveFile(Request.Files["SiteImage"], @"~/UploadedFiles", "SiteImage" + siteLocation.SiteId.ToString());
    }

    TryUpdateModel(siteLocation);

    if (!ModelState.IsValid)
        return View(siteLocation);  


    this._siteRepository.Save(User.Identity.Name);
    return RedirectToAction("SiteLocationDetails", new { id = siteLocation.SiteId });                                   
}

Here is my View containing a Partial View (shown later in this post)

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<Lms.Model.SiteLocation>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    <%= Html.Encode(Model.Site.SiteDescription) %>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<%=Html.Script("~/Scripts/jquery.textarea-expander.js")%>

    <%= Html.ValidationSummary("Location Create was unsuccessful. Please correct the errors and try again.\n If you uploaded images during this update please upload again.")%>
    <% using (

        Html.BeginForm
        (
            "SiteLocationEdit",
            "Site",
            FormMethod.Post,
           // add an encoding type attribute
           // that is required for file upload
            new { enctype = "multipart/form-data" }
        )

           )
       {%>
        <% Html.RenderPartial("SiteTabs", Model.Site); %>
        <div class="clear">
        </div>
        <% Html.RenderPartial("SiteLocationForm", Model); %>


    <% } %>

        <script type="text/javascript">
            /* jQuery textarea resizer plugin usage */
            $(document).ready(function() {
                jQuery("textarea[class*=expand]").TextAreaExpander(); // initialize all expanding textareas, new code, john s 10/08/2010
            });
        </script>

</asp:Content>

Here is the partial view :

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Lms.Model.SiteLocation>" %>
<fieldset>
    <div>
        <h3>
            <label id="Label2" style="text-align: left">
                <%= "Site Location: " + Html.Encode(Model.Site.SiteDescription) %></label>
        </h3>
    </div>
    <div class="formFields">
        <ul>
            <%--This is used to identify the site object to update when the model is returned to the controller--%>
            <%= Html.Hidden("SiteId", Model.SiteId)%>
            <li>
                <label for="Latitude">
                    <strong>Latitude:</strong></label>
                <%= Html.TextBox("Latitude")%>
                <%= Html.ValidationMessage("Latitude", "*")%>
            </li>
            <li>
                <label for="Longitude">
                    <strong>Longitude:</strong></label>
                <%= Html.TextBox("Longitude") %>
                <%= Html.ValidationMessage("Longitude", "*") %>
            </li>
            <li>
                <label for="Location">
                    <strong>Location Address:</strong></label>
                <label><%= Html.TextArea("Location", Model.Location, new { @class = "expand50-200"}) %></label>
                <%= Html.ValidationMessage("Location", "*") %>
            </li>
            <li>
                <label for="NearestPostcode">
                    <strong>Nearest Postcode:</strong></label>
                <%= Html.TextBox("NearestPostcode") %>
                <%= Html.ValidationMessage("NearestPostcode", "*") %>
            </li>
            <li>
                <label for="TimeFromOfficeToTurbine">
                    <strong>Office to Windfarm (Time):</strong></label>
                <%= Html.TextBox("TimeFromOfficeToTurbine") %>
                <%= Html.ValidationMessage("TimeFromOfficeToTurbine", "*") %>
            </li>
            <li>
                <label for="Directions">
                    <strong>Comments:</strong></label>
                <label><%= Html.TextArea("Directions", Model.Directions, new { @class = "expand50-200" })%> </label>
                <%= Html.ValidationMessage("Directions", "*") %>
            </li>

            <li>
            <h5><strong>For Image Uploads:</strong> Please use only JPG,JPEG or GIF formats.
            Image size should be appropriate for the webpage to display, approximately 500x375 (WidthxHeight)
            </h5>
            </li>

            <li>
                <label for="Site Plan">
                    <strong>Site Plan:</strong></label>
                <input id="SitePlan" name="SitePlan" type="file" />
            </li>

            <li>
                <label for="Site Image">
                    <strong>Site Image:</strong></label>
                <%--            <%//= Html.TextBox("SiteImage", Model.SiteImage)%>
            <%//= Html.ValidationMessage("SiteImage", "*") %>--%>
                <input id="SiteImage" name="SiteImage" type="file" />
            </li>


        </ul>
    </div>
</fieldset>
 <div class='demo'>
    <%=Html.ActionLink("< Back to List", "Index") %><input type="submit" value="Save" />
</div>

and here is the save file procedure in the controller code :

protected String SaveFile(HttpPostedFileBase file, String path, string name)
{
    if (file != null && file.ContentLength > 0)
    {
        if (path == null)
        {
            throw new ArgumentNullException("path cannot be null");
        }

        string fileType = file.FileName.Substring(file.FileName.LastIndexOf("."), file.FileName.Length - file.FileName.LastIndexOf("."));

        String relpath = String.Format("{0}/{1}", path, PrefixFName(name + fileType));
        try
        {
            file.SaveAs(Server.MapPath(relpath));
            return relpath;
        }
        catch (HttpException e)
        {
            throw new ApplicationException("Cannot save uploaded file", e);
        }
    }
    return null;
}

Here is the SiteLocationCreate() THIS WORKS, just the EDIT that does not :

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult SiteLocationCreate(SiteLocation siteLocation, FormCollection collection)
{
    // TODO CF: Look into this line.  Is there a better way to do it?  I would think so.
    // It uses a hidden field in the object form
    Site site = this._siteRepository.GetSite(Convert.ToInt16(collection["SiteId"]));                        
    site.SiteLocation = siteLocation;

    if (Request.Files.Count > 0 && Request.Files["SitePlan"].ContentLength > 0)
    {
        DeleteFile(siteLocation.SitePlan);
        siteLocation.SitePlan = SaveFile(Request.Files["SitePlan"], @"~/UploadedFiles", "SitePlan" + siteLocation.SiteId.ToString());
    }

    if (Request.Files.Count > 0 && Request.Files["SiteImage"].ContentLength > 0)
    {
        DeleteFile(siteLocation.SiteImage);
        siteLocation.SiteImage = SaveFile(Request.Files["SiteImage"], @"~/UploadedFiles", "SiteImage" + siteLocation.SiteId.ToString());
    }

    if (!ModelState.IsValid)              
        return View(siteLocation);                            

    this._siteRepository.Save(User.Identity.Name);
    return RedirectToAction("SiteLocationDetails", new { id = site.SiteId });                                   
}

解决方案

Removed TryUpdateModel() line and its working. But had to then specify line by line for each of the field updates, i.e. siteLocation.Location = collection["Location"]; etc etc. Since TryUpdateModel has been taken out

这篇关于System.Web.HttpPostedFileWrapper串在保存文件路径名,而不是的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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