溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

AJAX在C#中實(shí)現(xiàn)文件異步上傳

發(fā)布時(shí)間:2024-09-09 13:21:45 來源:億速云 閱讀:82 作者:小樊 欄目:編程語(yǔ)言

在C#中實(shí)現(xiàn)AJAX文件異步上傳,通常需要使用ASP.NET MVC或ASP.NET Core。這里我將為你提供一個(gè)簡(jiǎn)單的示例,展示如何在ASP.NET Core中實(shí)現(xiàn)AJAX文件異步上傳。

  1. 首先,創(chuàng)建一個(gè)新的ASP.NET Core項(xiàng)目,并添加以下NuGet包:

    • Microsoft.AspNetCore.Http
    • Microsoft.AspNetCore.Mvc
  2. 在項(xiàng)目中創(chuàng)建一個(gè)名為UploadController的控制器,并添加以下代碼:

using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

[Route("api/[controller]")]
[ApiController]
public class UploadController : ControllerBase
{
    [HttpPost]
    public async Task<IActionResult> Post()
    {
        try
        {
            var file = Request.Form.Files[0];
            var folderName = Path.Combine("Resources", "Images");
            var pathToSave = Path.Combine(Directory.GetCurrentDirectory(), folderName);

            if (file.Length > 0)
            {
                var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
                var fullPath = Path.Combine(pathToSave, fileName);
                using (var stream = new FileStream(fullPath, FileMode.Create))
                {
                    await file.CopyToAsync(stream);
                }
            }

            return Ok();
        }
        catch (Exception ex)
        {
            return StatusCode(500, $"Internal server error: {ex.Message}");
        }
    }
}
  1. wwwroot文件夾中創(chuàng)建一個(gè)名為index.html的HTML文件,并添加以下代碼:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>File Upload with AJAX</title>
   <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
   <input type="file" id="fileInput" />
   <button id="uploadButton">Upload</button>

   <script>
        $("#uploadButton").click(function () {
            const fileInput = document.getElementById("fileInput");
            const file = fileInput.files[0];
            const formData = new FormData();
            formData.append("file", file);

            $.ajax({
                url: "/api/upload",
                type: "POST",
                data: formData,
                processData: false,
                contentType: false,
                success: function (response) {
                    alert("File uploaded successfully!");
                },
                error: function (error) {
                    alert("Error during file upload: " + error.statusText);
                }
            });
        });
    </script>
</body>
</html>

現(xiàn)在,當(dāng)你運(yùn)行項(xiàng)目并訪問http://localhost:<port>/index.html時(shí),你可以選擇一個(gè)文件并使用AJAX異步上傳到服務(wù)器。上傳的文件將被保存在項(xiàng)目的Resources/Images文件夾中。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI