ASP.NET MVC实现简单的文件上传与下载

使用ASP.NET MVC实现简单的文件上传与下载。

1、上传文件HTML

<form action='@Url.Action("Upload", "File")' method="post" enctype="multipart/form-data">
    <input type="file" name="file" /><br />
    <input type="submit" value="提交" />
</form>

2、下载文件HTML

<a href='@Url.Action("Download", "File", new { fileName = "MyPhoto.png" })'>下载文件</a>

3、创建FileController.cs后台控制器

public class FileController : Controller
{
    /// <summary>
    /// 上传文件
    /// </summary>
    public ActionResult Upload(HttpPostedFileBase file)
    {
        var fileName = file.FileName;
        var filePath = Server.MapPath(string.Format("~/{0}", "File"));
        file.SaveAs(Path.Combine(filePath, fileName));
        return Json("上传成功");
    }

    /// <summary>
    /// 下载文件
    /// </summary>
    public FileStreamResult Download(string fileName)
    {
        string filePath = Server.MapPath(string.Format("~/{0}/{1}", "File", fileName));
        FileStream fs = new FileStream(filePath, FileMode.Open);
        return File(fs, "text/plain", fileName);
    }
}
相关文章
相关标签/搜索