隐藏

C# jquery ajax上传图片 webapi

发布:2022/5/25 22:43:31作者:管理员 来源:本站 浏览次数:1074

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

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

前端代码


<div>
        <input name="Userfile" id="Userfile" type="file">
        <input type="button" id="uploadfile" />
    </div>

<script>
        $(function () {
            $("#uploadfile").click(function () {
                var formDate = new FormData();
                var files = $("#Userfile").get(0).files;

                formDate.append("Userfile", files[0]);
                //如果有其他参需要一起提交到后台
                formDate.append("location", location);

                $.ajax({
                    type: "POST",
                    url: "http://localhost:6890/upload/imgs",
                    contentType: false,
                    cache: false,
                    processData: false,
                    data: formDate,
                    error: function (request) {
                        console.log(request);
                    },
                    success: function (data) {
                        console.log(data);
                    }
                });
            });
        });
    </script>


c#后端WebApi接口

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;

namespace OnlineApi.Controllers
{
    [RoutePrefix("upload")]
    public class UploadController : ApiController
    {
        [HttpPost, Route("imgs")]
        public bool UploadImgs()
        {
            //图片存储路径
            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;
            //var uploadPath = "/img/";
            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(path))
                    {
                        Directory.CreateDirectory(path);
                    }
                    file.SaveAs(filesrc);

                }
            }

            if (!string.IsNullOrEmpty(src))
            {
                //存储图片路径到数据库
            }
            return true;

        }
    }
}