正如标题所说,我正在下载一个文件,它做得很好,除非我暂停下载进度。我使用以下后端代码下载我的文件,它可以安装>10Gb的文件(最重要的)。
public void TransmitFileAsync()
{
System.IO.Stream iStream = null;
string fullPath = "D:\\backend-fileupload\\test.rar";
string outFileName = "test.rar";
// Buffer to read 10K bytes in chunk:
byte[] buffer = new Byte[10485760];
// Length of the file:
int length;
// Total bytes to read:
long dataToRead;
// Identify the file to download including its path.
string filepath = fullPath;
// Identify the file name.
string filename = Path.GetFileName(filepath);
try
{
// Open the file.
iStream = new FileStream(filepath, FileMode.Open,
FileAccess.Read, FileShare.Read);
// Total bytes to read:
dataToRead = iStream.Length;
Response.Clear();
Response.ContentType = "application/octet-stream";
Response.Headers.Add("Content-Disposition", "attachment; filename=" + outFileName );
/*Response.Headers.Add("Content-Type", "application/octet-stream");*/
Response.Headers.Add("Content-Length", iStream.Length.ToString());
Response.Headers.AcceptRanges = "bytes";
// Read the bytes.
while (dataToRead > 0)
{
CancellationToken cancellationToken = HttpContext.RequestAborted;
/* bool isPause = HttpContext.*/
// Verify that the client is connected.
// Read db auth ? or set in xml file and read
if (!cancellationToken.IsCancellationRequested && true)
{
// Read the data in buffer.
length = iStream.Read(buffer, 0, 10485760);
// Write the data to the current output stream.
Response.Body.Write(buffer, 0, length);
// Flush the data to the output.
Response.Body.Flush();
buffer = new Byte[10485760];
dataToRead = dataToRead - length;
}
else
{
//prevent infinite loop if user disconnects
dataToRead = -1;
}
}
}
catch (Exception ex)
{
throw new ApplicationException(ex.Message);
}
finally
{
if (iStream != null)
{
//Close the file.
iStream.Close();
}
Response.Body.Close();
}
}
字符串
前端:
fetch(requesturl, {
method: 'POST',
headers: {
'Content-Type': "application/octet-stream",
},
}).then(res => {
const readableStream = res.body;
const name = "test.rar"
const fileStream = streamSaver.createWriteStream(name, {
size: Number(res.headers.get("Content-Length"))
})
if (window.WritableStream && readableStream?.pipeTo) {
console.log('111done writing...')
return readableStream.pipeTo(fileStream).then(() => {
console.log('done writing...')
})
}
const reader = readableStream?.getReader();
const writer = fileStream.getWriter();
window.onunload = () => {
fileStream.abort()
// also possible to call abort on the writer you got from `getWriter()`
writer.abort()
}
const pump: any = () =>
reader?.read()
.then(res => res.done ? writer.close() : writer.write(res.value));
pump();
型
问题是:
enter image description hereenter image description here的数据库
我只知道当我暂停下载文件时,后端代码仍然在while()的循环中,我如何停止或暂停它来解决这个问题?
1条答案
按热度按时间imzjd6km1#
使用CacheControl并将其设置为“no-store”,则流无法拉入该高速缓存