【问题标题】:Upload file using $post jquery function使用 $post jquery 函数上传文件
【发布时间】:2012-09-25 10:36:36
【问题描述】:
 $(".btnSavePurpose").click(function(e){
       e.preventDefault();
       var item=$(this);
       $.post("url", 
                         item.closest("form").serialize(), function(data){
           if(data.Status=="Success")
           {
             //Let's replace the form with messsage                
             alert("Updated Successfully");
           }    
           else
           {
              alert(data.ErrorMessage);
           }

       });   
    });   

我想使用 ajax 发布我的表单。我使用了 $post() jquery 函数。我正在获取所有没有上传文件的数据。我已将 enctype 添加到表单中。我得到 Request.File["file"] null。如何检索上传的文件

<form method="post" id="profile-form" enctype="multipart/form-data">
   <table>
     <tr>
        <td style="width: 25%">
         Profile Name<span class="Require">&nbsp;*</span>
         </td>
         <td style="width: 10%">
          :
         </td>
          <td style="width: 70%">@Html.TextBoxFor(m => m.ProfileName, new { @class = "formTextBox" })
          </td>
   </tr>
   <tr>
       <td>
          My Ocupation<span class="Require">&nbsp;*</span>
       </td>
       <td>
       :
       </td>
       <td>@Html.TextBoxFor(m => m.Ocupation, new { @class = "formTextBox" })
       </td>
  </tr>
  <tr>
      <td>
         Upload New Profile Photo
      </td>
      <td>
         :
      </td>
      <td>
            <input type="file" name="file" id="file" runat="server" accept="gif|jpg|png|jpeg|bmp" />                                                       
      </td>
  </tr>
 </table>
 <input type="submit" id="btnSubmit" value="Submit" class="formButton" />
 </form>

【问题讨论】:

标签: jquery asp.net asp.net-mvc c#-4.0 file-upload


【解决方案1】:

恐怕你想要做的并不是这么简单。您无法使用 JavaScript 读取文件。您无权访问文件系统。这意味着您不能使用 AJAX 发布文件。 (嗯,它可以用 HTML5 完成 - 请参阅:How can I upload files asynchronously?

有很多方法可以解决这个问题,您可以自己快速拼凑起来的方法是将文件发布到 iframe 中。我建议为此使用 jQuery 插件,例如 http://blueimp.github.com/jQuery-File-Upload/

【讨论】:

【解决方案2】:

试试这个例子
html

<form id="form1" runat="server" enctype="multipart/form-data">
 <input type="file" id="myFile" name="myFile" />
 <asp:Button runat="server" ID="btnUpload" OnClick="btnUploadClick" Text="Upload" />
</form>

.net

 protected void btnUploadClick(object sender, EventArgs e)
    {
        HttpPostedFile file = Request.Files["myFile"];

        //check file was submitted
        if (file != null && file.ContentLength > 0)
        {
            string fname = Path.GetFileName(file.FileName);
            file.SaveAs(Server.MapPath(Path.Combine("~/App_Data/", fname)));
        }
    }

js怎么写看这里Using jQuery to send data from a multipart/form-data through ajax

【讨论】:

    猜你喜欢
    • 2012-06-18
    • 2011-04-22
    • 1970-01-01
    • 2021-08-28
    • 2012-12-05
    • 1970-01-01
    • 2013-11-29
    • 2015-12-06
    • 2014-01-11
    相关资源
    最近更新 更多