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");
            }
相关推荐
对象存储与RustFS2 分钟前
用 warp 压测 S3 兼容存储,十分钟跑出一份可复现的基准报告
后端·云原生·性能优化
用户298698530143 分钟前
Python 实现 Word 转 XPS、PostScript 与 OFD 格式
后端·python·api
蜗牛互联网28 分钟前
Python Agent 工具调用:审批令牌、参数白名单和累计预算
java·开发语言·人工智能·windows·后端·python
环境栈笔记28 分钟前
指纹浏览器检查代理失败怎么排查?先分清代理、网络和检测服务
前端·人工智能·后端·自动化
武子康1 小时前
ESP32 唤醒词标称 98%,为什么还要自己做验收?
人工智能·后端·agent
淡海水1 小时前
03-02-架构篇-Boehm GC架构解析
unity·架构·c#·gc·boehm
william_yangshun2 小时前
WordCraft 观察:纯 Rust 重写文字处理器,把文档变成可编程对象
开发语言·后端·rust·文档自动化
IT_陈寒2 小时前
SpringBoot开发实战:从入门到精通
前端·人工智能·后端
geovindu2 小时前
rust: pool Pattern (续)
开发语言·后端·设计模式·rust·对象池简写模式
一条泥憨鱼2 小时前
拦截器与过滤器:一次请求穿过 Spring 时,会先经过谁呢
java·开发语言·后端·spring