Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
596 views
in Technique[技术] by (71.8m points)

upload file using jquery and handler(ashx)

I am trying to upload a file using jquery ajax with handler (c#). The problem is, when I call the handler I get

context.Request.File.Count=0

Here is the aspx code:

<!--aspx file code-->
<script language="javascript" type="text/javascript">
$().ready(function () 
{
    $('#save').click(function (e)
    {
        CalluploaderHandler();
    });
});

function CalluploaderHandler()
{
    $.ajax({
                type: "POST",
                url: "Services/UPloader.ashx",
                contentType: "application/json; charset=utf-8",
                success: OnComplete,
                error: OnFail
            });
    return false;
}

function OnComplete(result)
{
    alert('Success');
}

function OnFail(result)
{
    alert('Request failed');
}

</script>
    </head>
        <body>
            <form  enctype="multipart/form-data">
                <label for="file">
                Filename:</label>
                <input name="file" id="file" type="file">
                <input id="save" name="submit" value="Submit" type="submit">
            </form>
        </body>
    </html>    

The c# code handler:

/* handler*/
public void ProcessRequest(HttpContext context)
{
    string savedFileName = "";

    foreach (string file in context.Request.Files)
    {
        HttpPostedFile hpf = context.Request.Files[file] as HttpPostedFile;
        if (hpf.ContentLength == 0)
            continue;
        // savedFileName = context.Server.MapPath(Path.GetFileName(hpf.FileName));
        // hpf.SaveAs(savedFileName);
    }
    context.Response.Write(savedFileName);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

i think the problem is with the contentType try

contentType: 'multipart/form-data',

OR

contentType :'application/octet-stream';

see this post for more information

Sending multipart/formdata with jQuery.ajax


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...