.net core中使用jquery文件上传

using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using SupplyHub_API.Models.CommonModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace SupplyHub_API.Controllers
{
    [Route("[controller]/[action]")]
    public class UploadController : Controller
    {
        private readonly IHostingEnvironment _env;
        public UploadController(IHostingEnvironment env)
        {
            _env = env;
        }

        public IActionResult UpLoadFile()
        {
            var files = Request.Form.Files;

            var now = DateTime.Now;
            var webRootPath = _env.WebRootPath;
            var filePath = @"/Uploads/Images/";

            if (!Directory.Exists(webRootPath + filePath))
            {
                try
                {
                    Directory.CreateDirectory(webRootPath + filePath);
                }
                catch
                {
                    return Json(new { code = 0, msg = "无法创建服务端{@root/Uploads/Images/}目录,请确认是否有操作权限!" });
                }
            }
            try
            {
                if (files.Count() > 0)
                {
                    List<UploadImageModel> list = new List<UploadImageModel>();
                    foreach (var uploadfile in files)
                    {
                        //文件后缀
                        var fileExtension = Path.GetExtension(uploadfile.FileName);

                        long fileSize = uploadfile.Length; //获得文件大小,以字节为单位
                        var strDateTime = DateTime.Now.ToString("yyMMddhhmmssfff"); //取得时间字符串
                        var strRan = Convert.ToString(new Random().Next(100, 999)); //生成三位随机数
                        var saveName = strDateTime + strRan + fileExtension;
                        //检查文件扩展名是否合法
                        if (!CheckFileExt(fileExtension))
                        {
                            return Json(new { code = 0, msg = "不允许上传" + fileExtension + "类型的文件", result = "no", message = "不允许上传" + fileExtension + "类型的文件" });
                        }
                        //检查文件大小是否合法
                        if (!CheckFileSize(fileSize))
                        {
                            return Json(new { code = 0, msg = "文件超过限制的大小" , result = "no", message = "文件超过限制的大小" });
                        }

                        using (FileStream fs = System.IO.File.Create(webRootPath + filePath + saveName))
                        {
                            uploadfile.CopyTo(fs);
                            fs.Flush();
                        }

                        list.Add(new UploadImageModel
                        {
                            filename = uploadfile.FileName,
                            url = $"{Request.Scheme}://{Request.Host}" + filePath.Replace("\\", "/") + saveName,
                        });
                    }
                    return Json(new { code = 1, msg = "上传成功", datas = list, result = "ok", message = "上传成功" });
                }
            }
            catch (Exception ex)
            {
                return Json(new { code = 0, msg = ex.Message, result = "no", message = "上传失败" });
                throw;
            }
            return Json(new { code = 0, msg = "上传失败", result = "no" ,message= "上传失败" });
        }

        /// <summary>
        /// 检查是否为合法的上传文件
        /// </summary>
        private bool CheckFileExt(string _fileExt)
        {
            //检查危险文件
            string[] excExt = { "asp", "aspx", "ashx", "asa", "asmx", "asax", "php", "jsp", "htm", "html" };
            for (int i = 0; i < excExt.Length; i++)
            {
                if (excExt[i].ToLower() == _fileExt.ToLower())
                {
                    return false;
                }
            }
            //检查合法文件
            string[] allowExt = (".gif,.jpg,.png,.bmp,.rar,.zip,.doc,.xls,.txt,.jpeg,.png").Split(',');
            for (int i = 0; i < allowExt.Length; i++)
            {
                if (allowExt[i].ToLower() == _fileExt.ToLower())
                {
                    return true;
                }
            }
            return false;
        }

        private bool CheckFileSize(long _fileSize)
        {
            if (_fileSize > 1024 * 1024 * 10)
            {
                return false;
            }
            return true;
        }
    }
}

  前端代码:

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>index</title>
    <script src="~/lib/jquery/dist/jquery.js"></script>
</head>
<body>
    <input id="uploaderInput" class="weui-uploader__input" type="file" accept="image/*" multiple="" name="img">
</body>
</html>

<script>
    $(function () {
        $("input[type=file]").change(function () {
            var file = $("input[type=file]")[0].files[0];
            uploadImag(file);
        });
    });


    function uploadImag(file) {
        var formData = new FormData();
        formData.append('file', file);
        $.ajax({
            //rver script to process data
            dataType: "json",
            url: 'http://10.12.78.28:8081/Upload/UpLoadFile',
            type: 'POST',
            success: function (data) {
                //success event
                console.log(data)
            },
            error: function (e) {
                //errorHandler
            },
            ///Form data
            data: formData,
            ///Options to tell JQuery not to process data or worry about content-type
            cache: false,
            contentType: false,
            processData: false
        });
    }
</script>

  

转载于:https://www.cnblogs.com/jhxk/articles/9341959.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值