C#结合JavaScript实现多文件上传
在C#中结合JavaScript实现多文件上传,通常涉及到前端的HTML和JavaScript代码以及后端的C#代码。以下是一个简单的示例:
前端HTML和JavaScript代码:
<form id="uploadForm" enctype="multipart/form-data">
<input type="file" id="fileUpload" multiple />
<input type="button" value="Upload" onclick="uploadFiles()" />
</form>
<script>
function uploadFiles() {
var files = document.getElementById('fileUpload').files;
var formData = new FormData();
for (var i = 0; i < files.length; i++) {
formData.append("file" + i, files[i]);
}
var xhr = new XMLHttpRequest();
xhr.open("POST", "/upload", true);
xhr.onload = function () {
if (this.status == 200) {
alert(this.responseText);
}
};
xhr.send(formData);
}
</script>
后端C#代码:
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.IO;
using System.Threading.Tasks;
[Route("[controller]")]
[ApiController]
public class UploadController : ControllerBase
{
[HttpPost("upload")]
public async Task<IActionResult> Upload(List<IFormFile> files)
{
var uploadsDir = Path.Combine(_env.WebRootPath, "uploads");
foreach (var file in files)
{
if (file.Length > 0)
{
var filePath = Path.Combine(uploadsDir, file.FileName);
using (var stream = new FileStream(filePath, FileMode.Create))
{
await file.CopyToAsync(stream);
}
}
}
return Ok("Files uploaded successfully.");
}
}
在这个示例中,前端JavaScript使用FormData
来收集文件,然后通过XMLHttpRequest
发送到后端的C# ASP.NET Core控制器。控制器中的Upload
方法接收多个上传的文件,并将它们保存到服务器的uploads
文件夹中。
确保你的ASP.NET Core项目配置了正确的路由和CORS策略,以允许从前端发起的跨域请求。
评论已关闭