zoukankan      html  css  js  c++  java
  • ajax C# webapi上传图片

    html ajax上传图片到服务器 后端采用asp.net webapi

    前端有各种现实上传图片的控件,样式可以做的很美观。我这里只用基本的样式做图片上传。

    前端代码

       <input name="Userfile" id="Userfile" type="file"></span>

    js代码

     var formDate = new FormData();
     var files = $("#Userfile").get(0).files;
      
     formDate.append("Userfile", files[0]);
    //如果有其他参需要一起提交到后台
    formDate.append("location", location);
    
      $.ajax({
                type: "POST",
                url: url,
                contentType: false,
                cache: false,
                processData: false,           
                data: formDate,
                error: function (request) {
                   
                },
                success: function (data) {
                   
                }
            });

    C# webapi代码

            [HttpPost]
            public object Save()
            {
               //图片存储路径
                string path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "img/";
               //用户提交的数据
                var Data = System.Web.HttpContext.Current.Request.Form;
                string filesrc = string.Empty;
                string src = string.Empty;
               //获取上传的文件
                var httpPostedFile = HttpContext.Current.Request.Files;
                if (httpPostedFile != null && httpPostedFile.Count > 0)
                {
                    var file = httpPostedFile[0];
                    string imgType = Path.GetExtension(file.FileName);
                    //限制文件上传类型
                    if (imgType.Contains(".jpg")|| imgType.Contains(".png")|| imgType.Contains(".bmp"))
                    {
                       string FileName = Guid.NewGuid().ToString() + imgType;
                       filesrc = path + FileName;
                       src = "/images/" + FileName;
                       // 如果目录不存在则要先创建
                       if (!Directory.Exists(uploadPath))
                       {
                          Directory.CreateDirectory(uploadPath);
                       }
    file.SaveAs(filesrc); }
    }
    if (!string.IsNullOrEmpty(src)) { //存储图片路径到数据库 } }
  • 相关阅读:
    通过json动态创建控制器
    记一次bug解决!改变思路解决问题的同时,还需要弄明白是什么原因。
    __proto__,prototype,constructor
    事件:compositionstart & compositionend,解决oninput获取到拼音的问题。
    事件绑定----阻止冒泡失效
    预装的win10系统如何恢复
    rem.js
    vscode 使用 github仓库
    nginx使用
    伸缩盒
  • 原文地址:https://www.cnblogs.com/jiezi/p/10429971.html
Copyright © 2011-2022 走看看