簡體   English   中英

使用 jQuery AJAX 和處理程序 (ashx) 上傳文件不起作用

[英]File Upload with jQuery AJAX and Handler (ashx) not working

我正在嘗試使用 jQuery AJAX 和通用處理程序上傳圖像文件。 但似乎文件沒有傳遞給處理程序。 提交后context.Request.Files[0]; 始終為空:-/

我究竟做錯了什么?

HTML:

<form id="form1" runat="server" method="post" enctype="multipart/form-data">

    <input name="file" id="file" type="file" />
    <input id="save" name="submit" value="Submit" type="submit" />

</form>

JS:

$().ready(function ()
{
    $('#file').change(function () 
    {
        sendFile(this.files[0]);
    });
});

function sendFile(file) 
{
    $.ajax({
        type: 'post',
        url: 'FileUpload.ashx',
        data: file,
        success: function () {
            // do something
        },
        xhrFields:
        {
            onprogress: function (progress) 
            {
                // calculate upload progress
                var percentage = Math.floor((progress.total / progress.totalSize) * 100);

                // log upload progress to console
                console.log('progress', percentage);

                if (percentage === 100) {
                    console.log('DONE!');
                }
            }
        },
        processData: false,
        contentType: 'multipart/form-data'
    });
}

ASHX:

public void ProcessRequest (HttpContext context) 
{
    HttpPostedFile file = context.Request.Files[0];

    if (file.ContentLength > 0)
    {
        //do something
    }
}

設法讓這個工作:)

這是我的代碼...

///create a new FormData object
var formData = new FormData(); //var formData = new FormData($('form')[0]);

///get the file and append it to the FormData object
formData.append('file', $('#file')[0].files[0]);

///AJAX request
$.ajax(
{
    ///server script to process data
    url: "fileupload.ashx", //web service
    type: 'POST',
    complete: function ()
    {
        //on complete event     
    },
    progress: function (evt)
    {
        //progress event    
    },
    ///Ajax events
    beforeSend: function (e) {
        //before event  
    },
    success: function (e) {
        //success event
    },
    error: function (e) {
        //errorHandler
    },
    ///Form data
    data: formData,
    ///Options to tell JQuery not to process data or worry about content-type
    cache: false,
    contentType: false,
    processData: false
});
///end AJAX request

當我實現這樣的事情時,我使用

var fd = new FormData();
fd.append(file.name,file);

在 ajax 調用中,發送fd

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM