Upload Image MVC always null

社会主义新天地 提交于 2019-12-20 05:47:05

问题


Hi everyone i am trying to upload a simple image but the HttpPostedFileBase is always remaining null. This is my code i dont know what i am doing wrong.

This is my code in the design view:

<fieldset>
    <legend>PictureModel</legend>

    <div class="editor-label">
        <%: Html.LabelFor(model => model.PrivacyTypeID) %>
    </div>
    <div class="editor-field">
        <%: Html.DropDownList("PrivacyTypeID", null, new { name = "PrivacyTypeID", title = "Please select privacy type.", id = "PrivacyTypeID" }) %>
        <%: Html.ValidationMessageFor(model => model.PrivacyTypeID) %>
    </div>
    <div class="editor-label">
        <%: Html.LabelFor(model => model.File1) %>
    </div>
    <div class="editor-field">
        **<input type="file" name="File1" />**
        <%: Html.ValidationMessageFor(model => model.File1) %>
    </div>        
    <div class="editor-label">
        <%: Html.LabelFor(model => model.Description) %>
    </div>

And here is the code in my controller:

public ActionResult AddPicture(Guid id, PictureModel model, HttpPostedFileBase File1) { try {

            if (ModelState.IsValid)
            {
                try
                {
                    Guid albumid = id;

                    if (File1 != null)
                    {
                        var physicalPath = Path.Combine(Server.MapPath("~/Gallery"), System.IO.Path.GetFileName(File1.FileName));
                        File1.SaveAs(physicalPath);
                        PicturesBL pictures = new PicturesBL();

Can anyone please tell me what is the problem??


回答1:


Can anyone please tell me what is the problem??

There's nothing wrong with the code you have shown. I suspect that the problem comes from the fact that you are submitting this form using an AJAX call and not a normal submit. But as you know you cannot upload files using AJAX. That's why your code is not working. If you want to upload files using AJAX you could use some client side plugin such as Uploadify or Fine uploader. This can also be done natively in HTML5 using the new File API. Of course this will only work in modern browsers that support it. If you need to support legacy browsers some of the available client side upload plugins might help you.




回答2:


This was driving me crazy too. After hours I realized, that

@Scripts.Render( "~/bundles/jquerymobile")

in _Layout.cshtml was causing the problem. When commented out, the upload worked.

See http://forum.jquery.com/topic/jquery-mobile-seems-to-clobber-ability-to-upload-files-via-forms for details.

Adding

data_ajax="false"
attribute to my form solved the problem.


回答3:


Be sure model.File1 type is HttpPostedFileBase not HttpPostedFile and form contains enctype = "multipart/form-data" attribute.



来源:https://stackoverflow.com/questions/16102235/upload-image-mvc-always-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!