要在ASP.NET MVC中实现用户上传文件并提供下载链接,可以按照以下步骤进行操作:
@using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
}
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
if (file != null && file.ContentLength > 0)
{
string fileName = Path.GetFileName(file.FileName);
string filePath = Path.Combine(Server.MapPath("~/App_Data/Uploads"), fileName);
file.SaveAs(filePath);
}
return RedirectToAction("Index");
}
public ActionResult Download(string fileName)
{
string filePath = Path.Combine(Server.MapPath("~/App_Data/Uploads"), fileName);
byte[] fileBytes = System.IO.File.ReadAllBytes(filePath);
return File(fileBytes, "application/octet-stream", fileName);
}
@Html.ActionLink("Download File", "Download", "Home", new { fileName = "example.txt" }, null)
这些代码示例演示了如何在ASP.NET MVC中实现用户上传文件并提供下载链接的功能。请注意,上传的文件将保存在服务器的指定文件夹中(在本例中为App_Data/Uploads
),下载链接将根据文件名调用Download
动作方法以下载文件。请根据实际需求进行适当的修改和调整。