ASP.NET简单文件上传

ASP.NET简单文件上传

文章目录


文件上传

注意文件上传的格式 enctype="multipart/form-data name="file""

java 复制代码
 <form action="/Route/UploadFile" method="post" enctype="multipart/form-data">
        <input type="file" name="file" value="" />
        <button>提交</button>
    </form>
java 复制代码
 public void UploadFile(HttpPostedFileBase file)
        {
            //文件上传,上传到本地项目的upload目录下
            //saveAs方法需要根路径,所有我们需要将相对路径转换成绝对路径
            string fileName = DateTime.Now.Ticks + file.FileName;
            string absolutePath = Request.MapPath(@"~/upload/");
            file.SaveAs(absolutePath + fileName);
            
        }

~表示项目的根路径

第二种

  • 从请求域中获取

    java 复制代码
    /// <summary>
            /// 文件上传
            /// </summary>
            /// <returns></returns>
            public ActionResult FileUpload()
            {
                //文件上传,上传到本地项目的upload目录下
                //saveAs方法需要根路径,所有我们需要将相对路径转换成绝对路径
                var absolutePath = Request.MapPath("~/upload/");
                Request.Files["file"].SaveAs(absolutePath + Request.Files["file"].FileName);
                //重定向
                Response.Redirect("http://www.baidu.com");
                return Content("成功");
            }

文件显示

  • 访问文件路径即可

    java 复制代码
      public ActionResult GetFile(string file)
            {
                //返回一张图片
                return File($@"~/upload/{file}","image/jpeg");
            }
相关推荐
拖孩10 分钟前
又又又用 AI 写了个小程序:我站起来猛蹬 AI,使劲薅羊毛
前端·后端·微信小程序
北冥有鱼18 分钟前
从 bean::method 里抠出注解:Java 方法引用元数据反查全记录
java·后端
CoderYanger1 小时前
Java EE 进阶:11. SpringBoot 统一功能处理(第四弹):@ControllerAdvice 源码分析+案例代码
java·数据库·spring boot·后端·spring·java-ee·mybatis
Sailing1 小时前
🔥🔥sql: waiting for connection 踩坑:不要一味调大 MaxOpenConns
后端·go·gin
一条Go3 小时前
ent + PostgreSQL:部分唯一索引怎么表达「全表最多一个」
后端·github
陈随易4 小时前
MoonBit 2026 深圳线下交流分享
前端·后端·程序员
HarmonSir5 小时前
Octop 架构解析(外番篇):两种多 Agent 协作,Octop 群聊房间 vs dsh 工单授权
后端·架构
tong_li5 小时前
给娃做个 AI 陪写作业助手:LangChain4j 入门(七):给工具循环上保险
后端·langchain
bai2735 小时前
13 个文件名里 4 个打不开:Node 能建、cmd 和 PowerShell 却读不了
javascript·后端
用户298698530145 小时前
使用 Python 提取 Word 文档中的文本与图片
后端·python·api