文件上传,通过AJAX中不要求在MVC中追加文件 [英] File upload through ajax does not append file in Request in MVC

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

问题描述

我有一个简单的形式,它包含了只接受图像文件类型的输入。 我只是要张贴的文件保存它的表,以及服务器。

I have a simple form which contains a input of type file which accepts only images. I just want to post the file save it in table as well as server.

下面是我的CSHTML

Below is my cshtml

@using (Html.BeginForm("UploadSlider", "Admin", FormMethod.Post, new { id = "frmUploadSliderImage", @class = "form-admin" }))
{
     <h2 class="form-login-heading">upload images</h2>
     <div class="login-wrap">
     <span class="btn btn-default btn-file">
     Browse <input type="file" id="sliderFile" multiple="multiple">
     </span>&nbsp;
     <span class="text-muted" id="filePlaceHolder">No files selected</span>
     <span class="text-danger"></span>
     <button class="btn btn-theme btn-block" name="upload" onclick="javascript: ValidateSliderImageandPost('frmUploadSliderImage', this);" id="btnUploadSliderImage" type="submit"><i class="fa fa-upload"></i> UPLOAD</button>
     </div>
}

这是我的js AJAX部分

this is my js ajax part

function ValidateSliderImageandPost(form, ctrl) {
    $("#" + form).on("submit", function (e) {
        e.preventDefault();
        var formContainer = $('#' + form + ' .text-danger');
        var formdata = new FormData();
        var fileInput = $('#sliderFile');
        if ($(fileInput).get(0).files.length == 0)
        {
            $('.btn-file :file').parent().siblings().filter(".text-danger").html('Please select a file!');
        }
        if ($(formContainer).text().length == 0) {
            run_waitMe('Uploading! Please wait...', 'stretch', '.container');
            $.each($(fileInput).get(0).files, function (index,value) {
                formdata.append($(this).attr('name'), $(this));
            });
            postData('UploadSlider', formdata, '.upslider .status');
            if (msg) {
                $(".container").find('#cont').waitMe('hide');
                $("#" + form).find('input[type=text], textarea').val('').removeClass("alert-success");
            }
            else {
                $(".container").find('#cont').waitMe('hide');
                $("#" + form).find('input[type=text], textarea').removeClass("alert-success");
            }

        }
        $("#" + form).unbind('submit');
        return false;
    });
}

function postData(url,data,target)
{
$.ajax({
    url: url,
    type: "POST",
    dataType: 'json',
    data: data,
    processData: false,
    contentType:false,
    success: function (data) {
        if (data.result) {
            animateStatus("success", data.message, target);
            msg = true;
        }
        else {
            animateStatus("fail", data.message, target);
            msg = false;
        }
    },
    error:
        function (data) {
            animateStatus("fail", data.message, target);
            msg = false;
        }
});
}

这是我的控制器部分

[HttpPost]
        public JsonResult UploadSlider()
        {
            bool valid = false;
            bool val = false;
            if (Request.Files.Count > 0)
            {
                valid = true;
            }
            else
            {
                return Json(new { result = false, message = "Something went wrong! Please try again!" });
            }
            if (valid)
            {
                List<string> fil = new List<string>();
                foreach (HttpPostedFileBase f in Request.Files)
                {
                    HttpPostedFileBase file = f; //Uploaded file
                    string fileName = file.FileName;
                    fil.Add("./Images/Galllery/" + fileName);
                    System.IO.Stream fileContent = file.InputStream;
                    file.SaveAs(Server.MapPath("~/Images/Gallery/") + fileName);
                }
                using (var context = new MCBConnectionString())
                {
                    foreach (string path in fil)
                    {
                        tbl_slider slider = new tbl_slider();
                        slider.slurl = path;
                        slider.slalt = "";
                        context.tbl_slider.Add(slider);
                        context.SaveChanges();
                        val = true;
                    }
                }
                if (val)
                {
                    return Json(new { result = true, message = "Uploaded video successfully." });
                }
                else
                {
                    return Json(new { result = false, message = "Could not upload video. Please try again!" });
                }
            }
            return Json(new { result = false, message = "Could not upload video. Please try again!" });


        }

当我调试,并检查Request.Files.Count它永远是零。是否有任何替代办法或我在做什么错误在发布该文件。我按照 链接,并根据我的需要所做的更改。

When I debug and check the Request.Files.Count it will always be zero. Is there any alternate workaround or am I doing any mistakes in posting the file. I have followed this link and have made changes according to my needs.

推荐答案

相反的:

$.each($(fileInput).get(0).files, function (index, value) {
    formdata.append($(this).attr('name'), $(this));
});

您可以使用:

$.each($(fileInput).get(0).files, function (index, value) {
    formdata.append(value.name, value);
});

主要的区别是,你的方法内容处置部分不包含文件名,因此ASP.NET不承认它作为一个文件内容:

The main difference is that with your approach the Content-Disposition part doesn't contain a filename and thus ASP.NET doesn't recognize it as a file content:

------WebKitFormBoundaryZxwCwBC0O8Q3hOAO
Content-Disposition: form-data; name="foo.png"

[object Object]
------WebKitFormBoundaryZxwCwBC0O8Q3hOAO
Content-Disposition: form-data; name="bar.png"

[object Object]
------WebKitFormBoundaryZxwCwBC0O8Q3hOAO--

和我的方式请求将是这样的:

and with my approach the request will look like this:

------WebKitFormBoundary1ERBVX0wzdVczcR0
Content-Disposition: form-data; name="foo.png"; filename="foo.png"
Content-Type: imag/png

[object Object]
------WebKitFormBoundary1ERBVX0wzdVczcR0
Content-Disposition: form-data; name="bar.png"; filename="bar.png"
Content-Type: image/png

[object Object]
------WebKitFormBoundary1ERBVX0wzdVczcR0--

现在你可以看到实际的区别。在第一种情况下,你没有一个文件名内容类型文件和ASP.NET简单地对待这些元素作为标准形式发布的数据,而不是文件。

Now you can see the actual difference. In the first case you don't have a filename nor Content-Type of the files and ASP.NET simply treat those elements as standard form posted data and not files.

此外,而不是使用实际文件名名称你可以考虑用它替换一些通用的一种:

Also instead of using the actual file name as name you may consider replacing it with some generic one:

$.each($(fileInput).get(0).files, function (index, value) {
    formdata.append('sliderFiles', value);
});

HttpPostedFileBase&GT; 参数,而不是使用 Request.Files 现在,你还可以通过有它采取名单,其中提高你的控制器动作$ C>:

Now you can further improve your controller action by having it take a List<HttpPostedFileBase> parameter instead of using Request.Files:

[HttpPost]
public ActionResult UploadSlider(List<HttpPostedFileBase> sliderFiles)
{
    ...
}

你的code的另一个要点是,HTML5 FORMDATA 不可为了浏览器和您的code将静默失败。如果你需要支持旧的浏览器,你可能需要通过测试浏览器的功能,并回落到一个标准的表单POST进行渐进增强,如果浏览器不支持FORMDATA:

Another remark about your code is that HTML5 FormData is not available in order browsers and your code will silently fail. If you need to support older browsers you might need to perform progressive enhancement by testing the capabilities of the browser and falling back to a standard form POST if the browser doesn't support FormData:

$("#" + form).on("submit", function (e) {
    if(window.FormData === undefined) {
        // The browser doesn't support uploading files with AJAX
        // falling back to standard form upload
    } else {
        // The browser supports uploading files with AJAX =>
        // we prevent the default form POST and use AJAX instead
        e.preventDefault();

        ...
    }
});

这篇关于文件上传,通过AJAX中不要求在MVC中追加文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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