ASP.NET如何报告上传进度?
创始人
2024-11-12 07:00:13
0

在ASP.NET中,可以使用AJAX或SignalR来报告文件上传进度。下面是使用AJAX的示例代码:

在前端,使用AJAX发送文件到服务器并报告进度:

function uploadFile() {
    var formData = new FormData();
    var fileInput = document.getElementById('fileInput');
    formData.append('file', fileInput.files[0]);

    var xhr = new XMLHttpRequest();
    xhr.open('POST', '/Upload/UploadFile', true);

    xhr.upload.onprogress = function (e) {
        if (e.lengthComputable) {
            var percent = (e.loaded / e.total) * 100;
            console.log('Progress: ' + percent + '%');
        }
    };

    xhr.onreadystatechange = function () {
        if (xhr.readyState === XMLHttpRequest.DONE) {
            if (xhr.status === 200) {
                console.log('Upload complete!');
            } else {
                console.log('Upload failed!');
            }
        }
    };

    xhr.send(formData);
}

在后端,创建一个控制器来处理文件上传:

public class UploadController : Controller
{
    [HttpPost]
    public ActionResult UploadFile(HttpPostedFileBase file)
    {
        if (file != null && file.ContentLength > 0)
        {
            // 处理文件上传
            // 可以在这里获取文件大小并进行进度报告
            // ...

            return Json(new { success = true });
        }

        return Json(new { success = false });
    }
}

在上述代码中,使用XMLHttpRequest.upload.onprogress事件来监听文件上传进度,并使用console.log在控制台输出进度信息。

请注意,由于安全限制,AJAX只能获取文件上传的进度,无法获取上传文件的大小。如果需要获取文件大小并实时报告进度,可以使用SignalR来实现。

相关内容

热门资讯

透视工具!wejoker黑侠辅... 透视工具!wejoker黑侠辅助器(透视)wepoker有没有机器人(竟然一直都是有挂)-哔哩哔哩1...
透视神器!hhpoker辅助挂... 透视神器!hhpoker辅助挂(透视)hhpoker到底可以作必弊码(原来一直总是有挂)-哔哩哔哩1...
透视神器!模拟器打开hhpok... 透视神器!模拟器打开hhpoker(透视)hhpoker免费透视脚本(切实有透视)-哔哩哔哩1、首先...
透视攻略!hh poker软件... 透视攻略!hh poker软件(透视)hhpoker德州机器人(原来一直总是有透视)-哔哩哔哩1、很...
透视软件!潮汕激k辅助(辅助)... 透视软件!潮汕激k辅助(辅助)新九五辅助微信脚本(其实存在有挂)-哔哩哔哩一、新九五辅助微信脚本可以...
透视脚本!aapoker脚本怎... 透视脚本!aapoker脚本怎么用(透视)aapoker怎么拿好牌(一贯一直都是有透视)-哔哩哔哩1...
透视攻略!hhpoker到底可... 透视攻略!hhpoker到底可以作必弊码(透视)德扑HHpoker有挂吗(一贯一直总是有辅助器)-哔...
透视app!德州透视插件(透视... 透视app!德州透视插件(透视)hhpoker辅助器(真是有透视)-哔哩哔哩1、在德州透视插件插件功...
透视攻略!拱趴大菠萝有挂吗(透... 透视攻略!拱趴大菠萝有挂吗(透视)pokemmo手机版透视脚本(总是是有辅助器)-哔哩哔哩1、不需要...
透视脚本!欢聚水鱼脚本(辅助)... 您好,jj斗地主捕鱼辅助这款游戏可以开挂的,确实是有挂的,需要了解加去威信【485275054】很多...