您好,登錄后才能下訂單哦!
在C#中實現AJAX文件異步上傳,通常需要使用ASP.NET MVC或ASP.NET Core。這里我將為你提供一個簡單的示例,展示如何在ASP.NET Core中實現AJAX文件異步上傳。
首先,創建一個新的ASP.NET Core項目,并添加以下NuGet包:
在項目中創建一個名為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}");
}
}
}
wwwroot
文件夾中創建一個名為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>
現在,當你運行項目并訪問http://localhost:<port>/index.html
時,你可以選擇一個文件并使用AJAX異步上傳到服務器。上傳的文件將被保存在項目的Resources/Images
文件夾中。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。