在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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。