Пример #1
0
        // GET: Upload
        /// <summary>
        /// 图片上传(Files)
        /// </summary>
        /// <returns></returns>
        public JsonResult UploadImageFile()
        {
            ItemResult <List <string> > result = new ItemResult <List <string> >();

            try
            {
                List <string> imgs = new List <string>();
                for (var i = 0; i < Request.Files.Count; i++)
                {
                    string fileurl = string.Empty;
                    var    file    = Request.Files[i];
                    var    length  = file.ContentLength;
                    string extName = System.IO.Path.GetExtension(file.FileName).ToLower();
                    if (ApplicationContext.AppSetting.AllowImageExt.IndexOf(extName.ToLower()) == -1)
                    {
                        result.Message = "请上传 " + ApplicationContext.AppSetting.AllowImageExt + "格式的图片";
                        return(Json(result));
                    }
                    byte[] myData = new Byte[length];
                    var    kb     = myData.Length * 1.0 / 1024;
                    if (kb > ApplicationContext.AppSetting.AllowImageSize)
                    {
                        result.Message = "请上传小于" + ApplicationContext.AppSetting.AllowImageSize + " KB的图片";
                        return(Json(result));
                    }
                    file.InputStream.Read(myData, 0, length);
                    var filename = DateTime.Now.ToString("yyyyMMddHHmmss") + DateTime.Now.Ticks + extName;

                    //本地存储
                    var Image_Upload_Path = Server.MapPath(ApplicationContext.AppSetting.Image_Upload_Path) + DateTime.Now.ToString("yyyyMMdd") + "/";
                    if (!Directory.Exists(Image_Upload_Path))
                    {
                        Directory.CreateDirectory(Image_Upload_Path);
                    }

                    FileStream newFile = new FileStream(Image_Upload_Path + filename, FileMode.Create, FileAccess.Write);
                    newFile.Write(myData, 0, myData.Length);
                    newFile.Close();
                    fileurl = filename;
                    //存储OSS
                    if (ApplicationContext.AppSetting.StorageMode == 2)
                    {
                        var res = imageService.ImageToOSS(filename, myData);
                        if (res.Success)
                        {
                            fileurl = res.Data;
                        }
                    }
                    imgs.Add(fileurl);
                }
                result.Success = true;
                result.Data    = imgs;
                return(Json(result));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }