其他分享
首页 > 其他分享> > 图片上传

图片上传

作者:互联网

public async Task<IActionResult> UploadFile()
        {
            ResultMsg result = new ResultMsg();
            string[] pictureFormatArray = ConfigValue.UploadFormat.Split(',');
            try
            {
                //获取上传图片文件
                var fileImg = HttpContext.Request.Form.Files[0];
                Stream userfile = fileImg.OpenReadStream();//.InputStream;
                string ext1 = Path.GetExtension(fileImg.FileName).ToLower();//获取文件扩展名(后缀)

                int UploadSize = int.Parse(ConfigValue.UploadFileSize);
                //判断文件大小不允许超过100Mb
                if (fileImg.Length > (UploadSize * 1024 * 1024))
                {
                    result.code = -1;
                    result.msg = "上传失败,文件大小超过100MB";
                    return Ok(result);
                }

                //检查文件后缀名
                if (!pictureFormatArray.Contains(ext1.TrimStart('.')))
                {
                    result.code = -1;
                    result.msg = "上传失败,文件格式必须为" + ConfigValue.UploadFormat + "类型";
                    return Ok(result);
                }
                using (HttpClient client = new HttpClient())
                {
                    var request = new HttpRequestMessage(HttpMethod.Post, ConfigValue.ServerImgaes + "/Upload/UploadImgageFromWeb?ImgPathEnum=" + 1 + "&IsFullPath=false" + "&ext=" + ext1.Substring(1));
                    var content = new MultipartFormDataContent();
                    content.Add(new StreamContent(userfile), "file", "file.jpg");
                    //content.Add(new StreamContent(HttpContext.Request.Form.Files[0].OpenReadStream()), "file", "file.jpg");
                    request.Content = content;

                    var response = await client.SendAsync(request);
                    response.EnsureSuccessStatusCode();

                    var filenamestr = await response.Content.ReadAsStringAsync();

                    result = JsonConvert.DeserializeObject<ResultMsg>(filenamestr);
                    //result.code = 1;
                    //result.msg = "上传成功";
                    //result.data = filenamestr;
                    return Ok(result);
                }
            }
            catch (Exception ex)
            {
                WriteLog.WriteLogs(ex, "");
                result.code = -1;
                result.msg = "上传失败";
                return Ok(result);
            }
        }

  

namespace NewFile.Common
{
    /// <summary>
    /// 获取配置信息
    /// </summary>
    public class ConfigValue {
        /// <summary>
        /// 上传格式
        /// </summary>
        public static string UploadFormat= CoinAppSettings.Instance.AppSettings.UploadFormat;

        /// <summary>
        /// 上传文件大小
        /// </summary>
        public static string UploadFileSize = CoinAppSettings.Instance.AppSettings.UploadFileSize;

        /// <summary>
        /// 上传文件路径
        /// </summary>
        public static string UploadFilePath = CoinAppSettings.Instance.AppSettings.UploadFilePath;
        /// <summary>
        /// 上传文件路径
        /// </summary>
        public static string ServerImgaes = CoinAppSettings.Instance.AppSettings.ServerImgaes;
        /// <summary>
        /// 上传文件路径
        /// </summary>
        public static string SaveToImgaes = CoinAppSettings.Instance.AppSettings.SaveToImgaes;
    }


    public class CoinAppSettings
    {
        public static CoinAppSettings Instance { get; private set; }

        public AppSettings AppSettings { get; }

        public DbConnection ConnectionStrings { get; }

        public static void CreateInstence(IConfigurationRoot builder)
        {
            Instance = new CoinAppSettings(builder);
        }

        public CoinAppSettings(IConfigurationRoot builder)
        {
            this.ConnectionStrings = new DbConnection(builder.GetSection("ConnectionStrings"));
            this.AppSettings = new AppSettings(builder.GetSection("AppSettings"));
        }
    }

    /// <summary>
    /// 链接配置
    /// </summary>
    public class DbConnection
    {
        /// <summary>
        /// 读数据库
        /// </summary>
        public string DapperRead { get; }
        /// <summary>
        /// 写数据库
        /// </summary>
        public string DapperWrite { get; }
        /// <summary>
        /// redis链接
        /// </summary>
        public string RedisConnMain { get; }
        public string RedisConnVice { get; }
        public string RabbitMqHostName { get; }
        public string RabbitMqUserName { get; }
        public string RabbitMqPassword { get; }
        public string RedisConnSignalr { get; }
        public DbConnection(IConfigurationSection section)
        {
            this.DapperRead = section.GetSection("DapperRead").Value;
            this.DapperWrite = section.GetSection("DapperWrite").Value;
            this.RedisConnMain = section.GetSection("RedisConnMain").Value;
            this.RedisConnVice = section.GetSection("RedisConnVice").Value;
            this.RabbitMqHostName = section.GetSection("RabbitMqHostName").Value;
            this.RabbitMqUserName = section.GetSection("RabbitMqUserName").Value;
            this.RabbitMqPassword = section.GetSection("RabbitMqPassword").Value;
            this.RedisConnSignalr = section.GetSection("RedisConnSignalr").Value;
        }
    }

    /// <summary>
    /// 常量配置
    /// </summary>
    public class AppSettings
    {
        /// <summary>
        /// 上传格式
        /// </summary>
        public string UploadFormat { get; }
       
        /// <summary>
        /// 上传文件大小
        /// </summary>
        public string UploadFileSize { get; }

        /// <summary>
        /// 上传文件路径
        /// </summary>
        public string UploadFilePath { get; }
        /// <summary>
        /// 上传文件路径
        /// </summary>
        public string ServerImgaes { get; }
        /// <summary>
        /// 上传文件路径
        /// </summary>
        public string SaveToImgaes { get; }

        /// <summary>
        /// 读取配置文件
        /// </summary>
        /// <param name="section"></param>
        public AppSettings(IConfigurationSection section)
        {
            this.UploadFormat = section.GetSection("UploadFormat").Value;
            this.UploadFileSize = section.GetSection("UploadFileSize").Value;
            this.UploadFilePath = section.GetSection("UploadFilePath").Value;
            this.ServerImgaes = section.GetSection("ServerImgaes").Value;
            this.SaveToImgaes = section.GetSection("SaveToImgaes").Value;
        }
    }
}

错误日志类

public static void WriteLogs(Exception ex = null, string LogAddress = "")
        {
            //此处理是否存在对应的错误日志文件夹
            if (ex==null)
            {
                StreamWriter fs = new StreamWriter(LogAddress, true);
                fs.WriteLine(LogAddress);
                fs.WriteLine();
                fs.Close();
            }
            else
            {
                var url = Environment.CurrentDirectory + "\\UploadLog";
                if (!Directory.Exists(url))
                {
                    //创建错误日志文件夹
                    Directory.CreateDirectory(url);
                }


                //如果日志文件为空,则默认在Debug目录下新建 YYYY-mm-dd_Log.log文件
                if (LogAddress == "")
                {
                    LogAddress = url + '\\' +
                        DateTime.Now.Year + '-' +
                        DateTime.Now.Month + '-' +
                        DateTime.Now.Day + "_Log.txt";
                }
                //把异常信息输出到文件,因为异常文件由这几部分组成,这样就不用我们自己复制到文档中了
                StreamWriter fs = new StreamWriter(LogAddress, true);
                fs.WriteLine("当前时间:" + DateTime.Now.ToString());
                fs.WriteLine("异常信息:" + ex.Message);
                fs.WriteLine("异常对象:" + ex.Source);
                fs.WriteLine("调用堆栈:\n" + ex.StackTrace.Trim());
                fs.WriteLine("触发方法:" + ex.TargetSite);
                fs.WriteLine();
                fs.Close();
            }
           
        }

  

标签:GetSection,string,get,section,result,上传,public,图片
来源: https://www.cnblogs.com/fangyyy/p/10599023.html