您好,登錄后才能下訂單哦!
在C#中實(shí)現(xiàn)AJAX文件異步上傳,通常需要使用ASP.NET MVC或ASP.NET Core。這里我將為你提供一個(gè)簡(jiǎn)單的示例,展示如何在ASP.NET Core中實(shí)現(xiàn)AJAX文件異步上傳。
首先,創(chuàng)建一個(gè)新的ASP.NET Core項(xiàng)目,并添加以下NuGet包:
在項(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}");
}
}
}
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
文件夾中。
免責(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)容。