C# 文件上传
时间: 2023-06-30 10:16:34 浏览: 82
在C#中进行文件上传,可以使用ASP.NET Web Forms或ASP.NET MVC框架中的控件或API来实现。以下是一个使用ASP.NET MVC框架的示例:
1. 在View中添加一个表单来上传文件:
```html
@using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="file" />
<input type="submit" value="Upload" />
}
```
2. 在Controller中添加一个接收文件上传请求的方法:
```csharp
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
if (file != null && file.ContentLength > 0)
{
// 可以在这里处理上传的文件
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
file.SaveAs(path);
return RedirectToAction("Index");
}
else
{
return View();
}
}
```
在上面的代码中,我们首先检查上传的文件是否为空且文件大小是否大于0。如果文件有效,则将其保存到服务器上的指定文件夹中,然后将用户重定向到主页。如果文件无效,则返回上传视图以供用户重试。
请注意,上面的代码仅作为示例,您可以根据您的实际需求进行修改和扩展。