ASP MVC中的图像上传错误

时间:2016-04-12 18:14:20

标签: asp.net asp.net-mvc base64 image-upload

我在尝试上传图片时遇到此问题。当我单击提交按钮时,出现以下错误:click

index code

当我使用withaut模态参数时,它可以工作,但窗口不是模态的,看起来很糟糕。

型号:

public partial class Prod
{
    public string PName { get; set; }
    public byte[] PFile{ get; set; }
}

索引视图:

  

@using(Html.BeginForm(" Create"," Products",FormMethod.Post,new {   enctype =" multipart / form-data" })){

                       @ Html.ActionLink("","创建","产品",null,新{data_modal ="文件",id =& #34; btnCreate",@ class =" btn btn-small   btn-primary pull-right fa fa-cart-plus" })

     

@ Html.ActionLink(""," Create"," Products",null,new {id =   " btnCreate",@ class =" btn btn-small btn-primary pull-right fa   FA-车加" })

}

创建视图:

    @using (Html.BeginForm("Create", "Products", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()

    <div class="modal-body">

        <div class="form-horizontal">
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })

            <div class="form-group">
                @Html.LabelFor(model => model.PFile, "Plik", htmlAttributes: new { @class = "control-label col-md-3" })
                <div class="col-md-9">
                    @Html.TextBoxFor(model => model.PFile, new { type = "file", name = "imageF" })
                    @Html.ValidationMessageFor(model => model.PFile, "", new { @class = "text-danger" })
                </div>
            </div>

        </div>

    </div>

    <div class="modal-footer">
        <button class="btn" data-dismiss="modal">Anuluj</button>
        <input class="btn btn-primary" type="submit" value="Zapisz" />
    </div>
}

控制器:

[HttpPost]
        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Exclude = "PFile")] Prod pro, HttpPostedFileBase imageF)
        {                    
            if (ModelState.IsValid)
            {

                    if (imageF != null)
                    {
                        pro.PName= imageF.ContentType;
                        pro.PFile= new byte[imageF.ContentLength];
                        imageF.InputStream.Read(pro.PFile, 0, imageF.ContentLength);
                    }


                     db.Prods.Add(pro);
                     db.SaveChanges();
                     return Json(new { success = true });

            }

            return PartialView("Create", pro);
        }

modalform.js

  

$(function(){

$.ajaxSetup({ cache: false });

$("a[data-modal]").on("click", function (e) {

    // hide dropdown if any
    $(e.target).closest('.btn-group').children('.dropdown-toggle').dropdown('toggle');


    $('#myModalContent').load(this.href, function () {


        $('#myModal').modal({
            /*backdrop: 'static',*/
            keyboard: true
        }, 'show');

        bindForm(this);
    });

    return false;
});
     

});

     

function bindForm(dialog){

$('form', dialog).submit(function () {
    $.ajax({
        url: this.action,
        type: this.method,
        data: $(this).serialize(),
        contentType: 'multipart/form-data',
        success: function (result) {
            if (result.success) {
                $('#myModal').modal('hide');
                //Refresh
                location.reload();
            } else {
                $('#myModalContent').html(result);
                bindForm();
            }
        }
    });
    return false;
}); }

请帮助解决这个问题。

3 个答案:

答案 0 :(得分:0)

尝试在Bind属性中包含HttpPostedFileBase对象的名称。您没有放入的任何内容都会被排除在请求之外。 像这样:

public ActionResult Create([Bind(Exclude = "PFile", Include = "imageF")] Prod pro, HttpPostedFileBase imageF)

答案 1 :(得分:0)

请检查一下。首先,你不能通过ajax调用发布文件。在服务器端发布文件需要完整的回发。还有一些其他技术可以处理来自ajax调用的文件。

检查此代码..

控制器功能。

public static int specialSum (int x){
    if(x == 1)  return 0;
    return ((x % 2 == 0) && (x % 7 != 0) ? specialSum(x - 1) + x   : specialSum(x - 1));
}

...视图模型

   public ActionResult Create(Prod pro)
    {
        if (ModelState.IsValid)
        {

            if (pro.PFile != null)
            {
                pro.PName = pro.PFile.ContentType;
                pro.PFileByte = new byte[pro.PFile.ContentLength];
                pro.PFile.InputStream.Read(pro.PFileByte, 0, pro.PFile.ContentLength);
            }


            //db.Prods.Add(pro);
            //db.SaveChanges();
            return Json(new { success = true });
        }
        return PartialView("Create", pro);
    }

删除表单提交功能并检查。如果需要ajax调用,请告诉我评论。

答案 2 :(得分:0)

提前抱歉我的英语不好!

使用此表单,您不需要使用ajax。确保有一个隐藏的PName输入或您发送给控制器的模型无效。我非常确定您需要有一个ID才能在数据库中添加数据,因此请将其添加到您的模型中,并确保您的变量pro具有有效的ID(数字)。

尝试使用此控制器上传文件。确保根据需要更改返回线! :

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Exclude = "PFile,PName")] Prod pro)
{                    
    if (ModelState.IsValid)
    {    
        try
        {
            if (Request.Files[0] != null && Request.Files[0].ContentLength > 0)
            {
                byte[] tmp = null;
                using (var bin = new BinaryReader(Request.Files[0].InputStream))
                {
                    tmp = bin.ReadBytes(Request.Files[0].ContentLength);
                }
                pro.PName = Request.Files[0].ContentType;
                pro.PFile = tmp;
            }
        }
        catch {
            throw new Exception("There is no file to upload.");
            // TODO Change the exception to this if your want your PFile and PName to be null if there's no file.
           // pro.PName = "";
           // pro.PFile = null;
        }
        db.Prods.Add(pro);
        db.SaveChanges();
        return RedirectToAction("Index", "Whatever");
    }
    return PartialView("Create", pro);
}