Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
531 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 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...