另一页上的asp.net文件输入帖子(使用ajax上传跨页脚本文件)

时间:2015-03-23 14:34:09

标签: c# jquery asp.net ajax asp.net-ajax

file.aspx

<form action="data/exec.aspx" method="post" enctype="multipart/form-data">
    <input type="file" name="image" required="required" id="image"/>
    <button type="submit">submit</button>
</form>

exec.aspx

HttpPostedFile file = Request.Files["image"];
if (file != null && file.ContentLength > 0 )
{
    try
    {
        string fname = Path.GetFileName(file.FileName);
        file.SaveAs(Server.MapPath(Path.Combine("../images/" + fname)));
        Response.Write("done " + fname);
    }
    catch (Exception ex)
    {
        Response.Write(ex);
    }
}

当我提交表单时,没有任何反应,文件为空。我也试过asp:file上传,但遇到了同样的问题。

类似的代码在exec.php页面$_FILES["image"]["name"]上的php示例上工作,它发布图像并保存,但它在ASP.NET跨页面帖子中不起作用。

1 个答案:

答案 0 :(得分:0)

 <form id="form1" runat="server" method="post" enctype="multipart/form-data">
<input type="file" name="doc" id="doc" />
    <button type="submit">Submit</button>
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script> 
<script src="http://malsup.github.com/jquery.form.js"></script> 
<script>
    $("form#form1").submit(function () {

        var formData = new FormData($(this)[0]);

        $.ajax({
            url: 'recive.aspx',
            type: 'POST',
            data: formData,
            async: false,
            success: function (data) {
                alert(data)
            },
            cache: false,
            contentType: false,
            processData: false
        });

        return false;
    });
</script>

我正在使用jquery和ajax发布来自其他表单的数据

<强> recive.aspx

HttpPostedFile file = Request.Files["doc"];
        if(file!=null)
        {
            string fname = Path.GetFileName(file.FileName);
            file.SaveAs(Server.MapPath(Path.Combine(fname)));
            Response.Write("done " + fname);
        }
        else
        {
            Response.Write("file empty");
        }