使用jQuery Ajax,HttpPostedfileBase为null [英] HttpPostedfileBase is null using jQuery Ajax

查看:150
本文介绍了使用jQuery Ajax,HttpPostedfileBase为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have problem with uploading file In Asp.net Mvc. First of all I should use Ajax to pass the upload file value.

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

In javascript I have model that I fill it, When I check it with debugger is correctly fill the object, but when I send this model to server (Controller )

httpPostedfileBase值始终为null。

The httpPostedfileBase value is Always null.

我在google上搜索它,在某些帖子中我看到我无法使用使用Ajax文件上传,但在其他地方,我看到我可以。

I search it on google, in some post I saw that I cant use file uploader with Ajax, but in other I saw that I can.

但我无法修复我的代码。

But I can not fix my Code.

有我的Javascript代码。

There is my Javascript Code.

$(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.");
          }
      });

我的控制器 public virtual bool SaveOneDatabase(ResturantSharingViewModel result)

我的ResturantSharingViewModel查看模型

My Controller public virtual bool SaveOneDatabase(ResturantSharingViewModel result) My ResturantSharingViewModel View Model

 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; }
}

我的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>

推荐答案

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

First, it's possible to upload with Ajax, the important thing is you need to set <form enctype="multipart/form-data"></form> on you form to tell it your form has an file upload input. Then you need to accept HttpPostedFileBase as an input parameter in your controller action.

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

Try this. Example of jquery upload code. (Taken mostly from How can I upload files asynchronously?)

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
    });
}

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

HTML Form needs this attribute. See this post why you need it -> What does enctype='multipart/form-data' mean?

enctype="multipart/form-data"

C#

[HttpPost]
public ActionResult SaveOneDatabase(HttpPostedFileBase file)
{
}

这篇关于使用jQuery Ajax,HttpPostedfileBase为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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