使用jQuery Ajax,HttpPostedfileBase为null

sal*_*lar 20 javascript asp.net-mvc

我在Asp.net Mvc上传文件时遇到问题.首先,我应该使用Ajax传递上传文件值.

在javascript我有我填充的模型,当我用调试器检查它是否正确填充对象,但当我将此模型发送到服务器(控制器)

httpPostedfileBase值始终为null.

我在谷歌搜索它,在一些帖子中我看到我不能使用文件上传器与Ajax,但在其他我看到我可以.

但我无法修复我的代码.

有我的Javascript代码.

$(document).ready(function () {

$('#btnUploadFile').on('click', function () {
   var data= new FormData();

    debugger;
    var files = $("#fileUpload").get(0).files;

    if (files.length > 0) {
        data.append("UploadedImage", files[0]);
    }
    var ResturantSharingViewModel =
   {
       Type: $("#SharingTargetType").val(),
       SharingTitle: $("#SharingTitle").val(),
       content: $("#Content").val(),
       ItemId : $("#ItemId").val(),
       Photos: files[0]
   };
    $.ajax({
        type: 'POST',
        dataType: 'json',
        contentType: 'application/json',
        url: '<%= Url.Action("SaveOneDatabase")%>',
        data: JSON.stringify(ResturantSharingViewModel),
          success: function (result) {
              var rs = result;
          },
          error: function () {
              alert("Error loading data! Please try again.");
          }
      });
Run Code Online (Sandbox Code Playgroud)

我的控制器public virtual bool SaveOneDatabase(ResturantSharingViewModel result) 我的ResturantSharingViewModel视图模型

 public class ResturantSharingViewModel
{
    public Guid SharingPremiumHistoryID { get; set; }
    public string SharingTitle { get; set; }
    public string Content { get; set; }
    public DateTime AddedDate { get; set; }
    public bool IsSubmit { get; set; }
    public DateTime SubmitedDate { get; set; }
    public IEnumerable<SelectListItem> SharingTypes { get; set; }
    public IEnumerable<SelectListItem> SharingTargetType { get; set; }
    public short Type { get; set; }
    public Guid ItemId { get; set; }
    public HttpPostedFileBase[] Photos { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我的Html元素

    <form enctype="multipart/form-data">
    <article>
    <%--<% =Html.BeginForm("Add","PremiumSharing") %>--%>
   <hgroup class="radiogroup">
    <h1>????? ???</h1>
    <%= Html.HiddenFor(model => model.SharingPremiumHistoryID) %>
    <%= Html.HiddenFor(model => model.ItemId) %>
    <div class="group">
        <span> ????? ?? </span>
        <%= Html.DropDownListFor(model => model.SharingTargetType, Model.SharingTypes) %>
    </div>
</hgroup>
<div class="newseditor">
    <div class="input-form">
        <%= Html.LabelFor(model => model.SharingTitle, "????? ???") %>
        <%= Html.TextBoxFor(model => model.SharingTitle) %>
    </div>

    <div class="input-form">
        <%= Html.LabelFor(model => model.Content, "??? ???") %>
        <%= Html.TextAreaFor(model => model.Content) %>
    </div>
    <div><input id="fileUpload" type="file" />

    </div>
    <% if (ViewBag.IsInEditMode != null && !(bool)ViewBag.IsInEditMode)
       {%>
    <div class="input-form">
        <%= Html.CheckBox("SendToInTheCity") %> ????? ?? ??? «?? ???» ???????
    </div>
    <%} %>

    <div class="input-submit">
        <button name="post" id="btnUploadFile"  onclick="uploadFile()" >????? ???</button>
    </div>
    <br />
</div>
Run Code Online (Sandbox Code Playgroud)

And*_*eas 14

首先,可以使用Ajax上传,重要的是你需要<form enctype="multipart/form-data"></form>在表单上设置告诉它你的表单有一个文件上传输入.然后,您需要接受HttpPostedFileBase控制器操作中的输入参数.

试试这个.jquery上传代码示例.(主要来自我如何异步上传文件?)

function uploadFile(uploadId) {
    var formData = new FormData($('form')[0]);

    $.ajax({
        url: '<%= Url.Action("SaveOneDatabase")%>',
        type: 'Post',
        beforeSend: function(){},
        success: function(result){

        },
        xhr: function() {  // Custom XMLHttpRequest
        var myXhr = $.ajaxSettings.xhr();
            if(myXhr.upload) { // Check if upload property exists
                // Progress code if you want
            }
            return myXhr;
        },
        error: function(){},
        data: formData,
        cache: false,
        contentType: false,
        processData: false
    });
}
Run Code Online (Sandbox Code Playgroud)

HTML表单需要此属性.看到这篇文章为什么你需要它 - > enctype ='multipart/form-data'是什么意思?

enctype="multipart/form-data"
Run Code Online (Sandbox Code Playgroud)

C#

[HttpPost]
public ActionResult SaveOneDatabase(HttpPostedFileBase file)
{
}
Run Code Online (Sandbox Code Playgroud)


Pra*_*hra 7

我修改了@a moradi 的答案。

JS:

//FormData:
//Consider it a normal form but with "multipart/form-data" encoding type.
//Inside it works same as XMLHttpRequest.send() method.    
var model = new FormData();
model.append("File", $('#file')[0].files[0]);
model.append("Name", "Name");
$.ajax({ 
        url: someUrl,
        type: "POST",
        data: model,
        //contentType: 
        //Sets the ContentType in header.
        //The default contentType is "application/x-www-form-urlencoded; charset=UTF-8". But this will prevent us sending AntiForgeryToken to service/controller.
        //To prevent this contentType is set to false.
        contentType: false,
        //processData:
        //To prevent data getting converted to string format, 'processData' option is set to false.
        processData: false,
        success = function (m) {...}
        error = function (m) {...}
    });
Run Code Online (Sandbox Code Playgroud)

查看型号:

public class PhotoAlbumViewModel {
    public  string Name { get; set; }
    public HttpPostedFileBase File { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

控制器:

public JsonResult AddPhoto(PhotoAlbumViewModel model) {
    ...
}
Run Code Online (Sandbox Code Playgroud)

参考:

有关详细信息,请参阅以下链接:FormDataJQueryContentType


小智 5

视图:

<script/>
var add_photo_url = "@Url.Action("AddPhoto", "Gallery")"; 
    var model = new FormData();    
    var i=0;//selected file index 
    model.append("File", files[i]);
    model.append("Name", "test");
    $.ajax({// and other parameter is set here 
        url: add_photo_url,
            type: "POST",
            data: model,
            dataType: "json",
            cache: false,
            contentType: false,
            processData: false

        })
        .always(function (result) { 
        });
</script>
Run Code Online (Sandbox Code Playgroud)

查看模型:

public class PhotoAlbumViewModel {
    public  string Name { get; set; }
    public HttpPostedFileBase File { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

控制器:

public JsonResult AddPhoto(PhotoAlbumViewModel model) {
    // var result =...
    // and set your result; 
    return Json(result, JsonRequestBehavior.AllowGet);
}
Run Code Online (Sandbox Code Playgroud)