溫馨提示×

asp.net fileupload怎樣實現斷點續傳

小樊
115
2024-12-06 08:14:04
欄目: 編程語言

在ASP.NET中,實現FileUpload的斷點續傳可以通過以下步驟來完成:

  1. 使用HTML5的<input type="file">元素來允許用戶選擇文件,并設置multiple屬性以允許選擇多個文件。
<input type="file" id="fileInput" multiple />
  1. 使用JavaScript監聽文件選擇框的change事件,并將選中的文件列表存儲在變量中。
let fileList = [];
document.getElementById('fileInput').addEventListener('change', function (event) {
    fileList = Array.from(event.target.files);
});
  1. 使用FormData對象來封裝文件數據,并設置Content-Range頭部以實現斷點續傳。
function uploadChunk(chunk, fileName, startIndex, totalChunks) {
    const formData = new FormData();
    formData.append('file', chunk, fileName);
    formData.append('startIndex', startIndex);
    formData.append('totalChunks', totalChunks);

    fetch('/upload', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            console.log('Chunk uploaded successfully');
        } else {
            console.error('Chunk upload failed:', data.message);
        }
    })
    .catch(error => {
        console.error('Error uploading chunk:', error);
    });
}
  1. 在服務器端,使用ASP.NET Core Web API來處理文件上傳請求。在處理上傳時,需要檢查請求中是否包含Content-Range頭部,并根據該頭部來確定當前上傳的文件的起始位置和總塊數。
[HttpPost("upload")]
public async Task<IActionResult> UploadChunk([FromBody] byte[] chunk, [FromForm] string fileName, [FromForm] long startIndex, [FromForm] int totalChunks)
{
    // 檢查文件是否已經上傳完畢
    if (totalChunks == 1)
    {
        // 將文件保存到服務器
        var filePath = Path.Combine(Directory.GetCurrentDirectory(), "uploads", fileName);
        File.WriteAllBytes(filePath, chunk);
        return Ok();
    }

    // 獲取文件的臨時路徑
    var tempPath = Path.Combine(Path.GetTempPath(), "uploads", fileName);

    // 將當前塊追加到文件中
    File.AppendAllBytes(tempPath, chunk);

    // 更新已上傳的總塊數
    var totalBytesUploaded = new FileInfo(tempPath).Length;
    var totalChunksUploaded = GetTotalChunksUploaded(fileName);
    SetTotalChunksUploaded(fileName, totalChunksUploaded + 1);

    // 檢查所有塊是否已上傳完畢
    if (totalBytesUploaded == GetFileSize(fileName))
    {
        // 將文件移動到最終位置
        var finalPath = Path.Combine(Directory.GetCurrentDirectory(), "uploads", fileName);
        File.Move(tempPath, finalPath);
        return Ok();
    }

    return Ok();
}
  1. 在客戶端,根據服務器端返回的響應來決定是否繼續上傳下一個文件塊。
function continueUpload() {
    const file = fileList[0];
    const startIndex = GetStartIndexOfUploadedChunk(file.name);
    const totalChunks = GetTotalChunks(file.name);
    const chunkSize = 1024 * 1024; // 1MB

    for (let i = startIndex; i < totalChunks; i++) {
        const start = i * chunkSize;
        const end = Math.min(start + chunkSize, GetFileSize(file.name));
        const chunk = GetChunkFromFile(file.name, start, end);

        uploadChunk(chunk, file.name, start, totalChunks);
    }
}

通過以上步驟,可以實現一個基本的斷點續傳功能。在實際應用中,還需要考慮更多的細節,例如錯誤處理、并發控制、文件分片等。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女