gpt4 book ai didi

c# - 如果浏览器关闭/上传取消,如何停止文件传输

转载 作者:太空狗 更新时间:2023-10-30 01:24:48 25 4
gpt4 key购买 nike

我正在使用 MVC3 中的 HTML5 异步上传文件。如果我有一个大文件,比如 1GB,在上传完成 50% 后我取消上传或关闭浏览器,它仍然会在目标文件夹中保存一个 500MB 的文件。

我如何在 Controller 和客户端处理这个问题?

这是我的 Controller Action :

[HttpPost]
public ActionResult Upload(object fileToUpload1)
{
var fileName = Request.Headers["X-File-Name"];
var fileSize = Request.Headers["X-File-Size"];
var fileType = Request.Headers["X-File-Type"];

Request.SaveAs("D:\\uploadimage\\" + fileName, false);

if (fileToUpload1 == null)
{
return Json(true, JsonRequestBehavior.AllowGet);
}
else { return Json(false, JsonRequestBehavior.AllowGet); }

// return Json(false, JsonRequestBehavior.AllowGet);
}

这是 Javascript:

// Uploading - for Firefox, Google Chrome and Safari
xhr = new XMLHttpRequest();

// Update progress bar
xhr.upload.addEventListener("progress", uploadProgress, false);

function uploadProgress(evt) {
if (evt.lengthComputable) {
var percentComplete = Math.round(evt.loaded * 100 / evt.total);

//assign value to prgress bar Div
var progressBar = document.getElementById("progressBar");

progressBar.max = evt.total;
progressBar.value = evt.loaded;
}
}

// File load event
xhr.upload.addEventListener("load", loadSuccess, false);

function loadSuccess(evt) {
$(fileParentDivobj).find(".ImgDiv").find("span").html("uploaded");
addfile(fileParentDivobj);
}

//handling error
xhr.addEventListener("error", uploadFailed, false);
xhr.addEventListener("abort", uploadCanceled, false);

function uploadFailed(evt) {
alert("There was an error attempting to upload the file.");
}

function uploadCanceled(evt) {
alert("The upload has been canceled by the user or the browser dropped the connection.");
}

xhr.open("POST", "@Url.Action("Upload","Home")", true);

// Set appropriate headers
xhr.setRequestHeader("Cache-Control", "no-cache");
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.setRequestHeader("Content-Type", "multipart/form-data");
xhr.setRequestHeader("X-File-Name", file.fileName);
xhr.setRequestHeader("X-File-Size", file.fileSize);
xhr.setRequestHeader("X-File-Type", file.type);
xhr.setRequestHeader("X-File", file);

// Send the file (doh)
xhr.send(file);

最佳答案

首先,这不是应该使用任何客户端脚本解决的问题,因为我不相信您将能够在浏览器关闭时发出新请求,并且在连接中断时它肯定不会工作,因为网络问题。

所以我进行了一些挖掘,但在 asp.net 中没有发现任何可以告诉我请求连接已中断的信息。然而,我们可以检查我们收到了多少数据以及我们应该收到多少数据!

public ActionResult Upload()
{
// I like to keep all application data in App_Data, feel free to change this
var dir = Server.MapPath("~/App_Data");
if (!Directory.Exists(dir))
Directory.CreateDirectory(dir);

// extract file name from request and make sure it doesn't contain anything harmful
var name = Path.GetFileName(Request.Headers["X-File-Name"]);
foreach (var c in Path.GetInvalidFileNameChars())
name.Replace(c, '-');

// construct file path
var path = Path.Combine(dir, name);

// this variable will hold how much data we have received
var written = 0;
try
{
using (var output = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None))
{
var buffer = new byte[0x1000];
var read = 0;

// while there is something to read, write it to output and increase counter
while ((read = Request.InputStream.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, read);
output.Flush();

written += read;
}
}
}
finally
{
// once finished (or when exception was thrown) check whether we have all data from the request
// and if not - delete the file
if (Request.ContentLength != written)
System.IO.File.Delete(path);
}

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

使用 asp.net dev 服务器和 google chrome 对您的客户端代码进行了测试。

编辑:刚刚注意到 Chuck Savage 之前在评论中发布了这个原则,所以支持他 :)

关于c# - 如果浏览器关闭/上传取消,如何停止文件传输,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8397572/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com