예제 #1
0
        public void ProcessRequest(HttpContext context)
        {
            #region 检查是否登录
            currentUserInfo = bllWebsiteDomainInfo.GetCurrentUserInfo();
            if (currentUserInfo == null)
            {
                resp.Msg = "您还未登录";
                context.Response.Write(Common.JSONHelper.ObjectToJson(resp));
                return;
            }
            websiteOwner = bllWebsiteDomainInfo.WebsiteOwner;
            #endregion

            OssSign ossSign = new OssSign();
            try
            {
                ossSign = OssHelper.BuildSign(OssHelper.GetBucket(websiteOwner), OssHelper.GetBaseDir(websiteOwner), currentUserInfo.UserID, context.Request["fd"], null);
            }
            catch (Exception ex)
            {
                resp.Msg = ex.Message;
                context.Response.Write(Common.JSONHelper.ObjectToJson(resp));
                return;
            }

            resp.IsSuccess = true;
            resp.Result    = ossSign;
            context.Response.Write(Common.JSONHelper.ObjectToJson(resp));
            return;
        }
예제 #2
0
파일: Form2.cs 프로젝트: uvbs/mmp
        private void button1_Click(object sender, EventArgs e)
        {
            string oldFile1 = textBox1.Text.Trim();

            byte[] fileByte  = File.ReadAllBytes(oldFile1);
            string extension = Path.GetExtension(oldFile1).ToLower();

            OssHelper.UploadFileFromByte(OssHelper.GetBucket(""), "oldsite/FileUpload/mixblu/20151012/image/839cc17c-e7e3-4413-bb1a-55880a30c6af.jpg", fileByte, extension);
        }
예제 #3
0
        public string upload(WebsiteInfo websiteInfo, string userId, Stream fileStream, string fileExtension)
        {
            string fileUrl = "";

            //判断是否有用到微软云
            if (HasWindowsAzure(websiteInfo))
            {
                //AZStorage.Client azClient = new AZStorage.Client("ehtwshopoos", "+8nN68pmvaGax4UqrowjKFbjKikPatgk/hLOZjDMzwJ8YORztDl3vQo2JyDnhYdWkEiJ4+4mXyP0KHA5gL2tOw==", "ehtwshopimg");
                AZStorage.Client azClient = new AZStorage.Client(websiteInfo.AzureAccountName, websiteInfo.AzureAccountKey, websiteInfo.AzureContainerName);
                fileUrl = azClient.upload(fileStream, fileExtension);
            }
            else
            {
                fileUrl = OssHelper.UploadFileFromStream(OssHelper.GetBucket(websiteInfo.WebsiteOwner), OssHelper.GetBaseDir(websiteInfo.WebsiteOwner), userId, "image", fileStream, fileExtension);
            }

            return(fileUrl);
        }
예제 #4
0
파일: File.ashx.cs 프로젝트: uvbs/mmp
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private string Add(HttpContext context)
        {
            //定义允许上传的文件扩展名
            Hashtable extTable = new Hashtable();

            extTable.Add("image", "gif,jpg,jpeg,png,bmp");
            extTable.Add("flash", "swf,flv");
            extTable.Add("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
            extTable.Add("file", "doc,docx,xls,xlsx,ppt,pdf,htm,html,txt,zip,rar,gz,bz2,mp3,wmv");
            extTable.Add("app", "apk,app,ipa");

            String dirName = context.Request["dir"];

            if (String.IsNullOrEmpty(dirName))
            {
                dirName = "image";
            }

            webSiteInfo = bll.GetWebsiteInfoModel();
            if (webSiteInfo == null)
            {
                return(ZentCloud.Common.JSONHelper.ObjectToJson(new
                {
                    errcode = 2,
                    errmsg = "找不到站点信息。"
                }));
            }
            currentUserInfo = bll.GetCurrentUserInfo();
            if (currentUserInfo != null)
            {
                userId = currentUserInfo.UserID;
            }
            else
            {
                userId = "other";
            }

            List <string>  fileUrlList   = new List <string>();
            List <dynamic> otherInfoList = new List <dynamic>();

            var postFileList = context.Request.Files;

            for (int i = 0; i < postFileList.Count; i++)
            {
                String fileName = postFileList[i].FileName;
                String fileExt  = Path.GetExtension(fileName).ToLower();

                if (String.IsNullOrEmpty(fileExt) || Array.IndexOf(((String)extTable[dirName]).Split(','), fileExt.Substring(1).ToLower()) == -1)
                {
                    return(ZentCloud.Common.JSONHelper.ObjectToJson(new
                    {
                        errcode = 1,
                        errmsg = "上传文件扩展名是不允许的扩展名。\n只允许" + ((String)extTable[dirName]) + "格式。"
                    }));
                }
                try
                {
                    int maxWidth  = 800;
                    int maxHeight = 0;
                    if (!string.IsNullOrWhiteSpace(context.Request["maxWidth"]))
                    {
                        maxWidth = Convert.ToInt32(context.Request["maxWidth"]);
                    }
                    if (!string.IsNullOrWhiteSpace(context.Request["maxHeight"]))
                    {
                        maxHeight = Convert.ToInt32(context.Request["maxHeight"]);
                    }
                    if (dirName == "image" && (maxWidth > 0 || maxHeight > 0))
                    {
                        ZentCloud.Common.ImgWatermarkHelper imgHelper = new ZentCloud.Common.ImgWatermarkHelper();
                        Image image = Image.FromStream(postFileList[i].InputStream);

                        if ((image.Width > maxWidth && maxWidth > 0) || (image.Height > maxHeight && maxHeight > 0))
                        {
                            double ratio     = imgHelper.GetRatio(image.Width, image.Height, maxWidth, maxHeight);
                            int    newWidth  = Convert.ToInt32(Math.Round(ratio * image.Width));
                            int    newHeight = Convert.ToInt32(Math.Round(ratio * image.Height));
                            image = imgHelper.PhotoSizeChange(image, newWidth, newHeight);
                        }
                        if (ZentCloud.Common.ConfigHelper.GetConfigInt("Oss_Enable") == 0)
                        {
                            //文件保存目录路径
                            String fname      = Guid.NewGuid().ToString("N").ToUpper() + fileExt;
                            String savePath   = "/FileUpload/" + dirName + "/" + bll.WebsiteOwner + "/" + userId + "/" + DateTime.Now.ToString("yyyyMMdd", DateTimeFormatInfo.InvariantInfo) + "/";
                            String serverPath = context.Server.MapPath(savePath);
                            if (!Directory.Exists(serverPath))
                            {
                                Directory.CreateDirectory(serverPath);
                            }
                            String serverFile = serverPath + fname;
                            String saveFile   = savePath + fname;
                            image.Save(serverFile, imgHelper.GetImageFormat(fileExt));

                            fileUrlList.Add(saveFile);

                            otherInfoList.Add(new
                            {
                                width      = image.Width,
                                height     = image.Height,
                                old_name   = postFileList[i].FileName,
                                filelength = postFileList[i].ContentLength
                            });
                        }
                        else
                        {
                            Stream stream = new MemoryStream();
                            image.Save(stream, imgHelper.GetImageFormat(fileExt));
                            stream.Position = 0;

                            string fileUrl = bllUploadOtherServer.upload(stream, fileExt); //= OssHelper.UploadFileFromStream(OssHelper.GetBucket(webSiteInfo.WebsiteOwner), OssHelper.GetBaseDir(webSiteInfo.WebsiteOwner), userId, "image", stream, fileExt);

                            fileUrlList.Add(fileUrl);

                            otherInfoList.Add(new
                            {
                                width      = image.Width,
                                height     = image.Height,
                                old_name   = postFileList[i].FileName,
                                filelength = postFileList[i].ContentLength
                            });
                        }
                    }
                    else
                    {
                        if (ZentCloud.Common.ConfigHelper.GetConfigInt("Oss_Enable") == 0)
                        {
                            //文件保存目录路径
                            String fname      = Guid.NewGuid().ToString("N").ToUpper() + fileExt;
                            String savePath   = "/FileUpload/" + dirName + "/" + bll.WebsiteOwner + "/" + userId + "/" + DateTime.Now.ToString("yyyyMMdd", DateTimeFormatInfo.InvariantInfo) + "/";
                            String serverPath = context.Server.MapPath(savePath);
                            if (!Directory.Exists(serverPath))
                            {
                                Directory.CreateDirectory(serverPath);
                            }
                            String serverFile = serverPath + fname;
                            String saveFile   = savePath + fname;
                            fileUrlList.Add(saveFile);
                            if (dirName == "image")
                            {
                                ZentCloud.Common.ImgWatermarkHelper imgHelper = new ZentCloud.Common.ImgWatermarkHelper();
                                Image image = Image.FromStream(postFileList[i].InputStream);
                                image.Save(serverFile, imgHelper.GetImageFormat(fileExt));
                                otherInfoList.Add(new
                                {
                                    width      = image.Width,
                                    height     = image.Height,
                                    old_name   = postFileList[i].FileName,
                                    filelength = postFileList[i].ContentLength
                                });
                            }
                            else
                            {
                                postFileList[i].SaveAs(serverFile);
                                otherInfoList.Add(new
                                {
                                    old_name    = postFileList[i].FileName,
                                    file_length = postFileList[i].ContentLength
                                });
                            }
                        }
                        else
                        {
                            String fileUrl = OssHelper.UploadFile(OssHelper.GetBucket(webSiteInfo.WebsiteOwner), OssHelper.GetBaseDir(webSiteInfo.WebsiteOwner), userId, dirName, postFileList[i]);
                            fileUrlList.Add(fileUrl);

                            if (dirName == "image")
                            {
                                Image image = Image.FromStream(postFileList[i].InputStream);
                                otherInfoList.Add(new
                                {
                                    width      = image.Width,
                                    height     = image.Height,
                                    old_name   = postFileList[i].FileName,
                                    filelength = postFileList[i].ContentLength
                                });
                            }
                            else
                            {
                                otherInfoList.Add(new
                                {
                                    old_name    = postFileList[i].FileName,
                                    file_length = postFileList[i].ContentLength
                                });
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    if (ZentCloud.Common.ConfigHelper.GetConfigInt("Oss_Enable") == 0)
                    {
                        return(ZentCloud.Common.JSONHelper.ObjectToJson(new
                        {
                            errcode = 4,
                            errmsg = "上传出错:" + ex.Message
                        }));
                    }
                    else
                    {
                        return(ZentCloud.Common.JSONHelper.ObjectToJson(new
                        {
                            errcode = 4,
                            errmsg = "上传到Oss出错:" + ex.Message
                        }));
                    }
                }
            }
            //
            if (fileUrlList.Count > 0)
            {
                return(ZentCloud.Common.JSONHelper.ObjectToJson(new
                {
                    errcode = 0,
                    errmsg = "ok",
                    file_url_list = fileUrlList,
                    other_info_list = otherInfoList
                }));
            }
            else
            {
                return(ZentCloud.Common.JSONHelper.ObjectToJson(new
                {
                    errcode = 1,
                    errmsg = "fail"
                }));
            }
        }
예제 #5
0
파일: Form1.cs 프로젝트: uvbs/mmp
        private void ToOss2(DataTable dt)
        {
            StringBuilder sb = new StringBuilder();

            foreach (DataRow dr in dt.Rows)
            {
                try
                {
                    string oldFile = dr[txt2].ToString();
                    if (string.IsNullOrWhiteSpace(oldFile))
                    {
                        continue;
                    }
                    string oldFile1 = "";

                    if (oldFile.StartsWith(OssHelper.GetDomain()))
                    {
                        SetTextErrorMessage("已经在Oss服务器:" + oldFile);
                        continue;
                    }
                    else if (oldFile.StartsWith("/"))
                    {
                        oldFile1 = oldFile;
                    }
                    else
                    {
                        bool   haveLocalSrc = false;
                        string nowWebDomain = "";
                        for (int i = 0; i < txtLikeWebDomain.Length; i++)
                        {
                            if (oldFile.IndexOf(txtLikeWebDomain[i]) > 0)
                            {
                                haveLocalSrc = true;
                                nowWebDomain = txtLikeWebDomain[i];
                                break;
                            }
                        }
                        if (!haveLocalSrc)
                        {
                            SetTextErrorMessage("不是本站图片:" + oldFile);
                            continue;
                        }

                        oldFile1 = oldFile.Substring(oldFile.IndexOf(nowWebDomain) + nowWebDomain.Length - 1);
                    }
                    SetTextErrorMessage(oldFile1);
                    string  url = "";
                    DataSet ds  = DbHelperSQL.Query(string.Format("SELECT TOP 1 OldPath,NewPath FROM {0} WHERE OldPath='{1}' ", "FileToOssLog", oldFile1));
                    if (ds != null && ds.Tables.Count != 0 && ds.Tables[0].Rows.Count == 1)
                    {
                        url = ds.Tables[0].Rows[0]["NewPath"].ToString();
                    }
                    if (string.IsNullOrWhiteSpace(url))
                    {
                        ds = DbHelperSQL.Query(string.Format("SELECT TOP 1 OldPath,NewPath FROM {0} WHERE OldPath='{1}' ", "FileToOssLog", oldFile));
                        if (ds != null && ds.Tables.Count != 0 && ds.Tables[0].Rows.Count == 1)
                        {
                            url = ds.Tables[0].Rows[0]["NewPath"].ToString();
                        }
                    }
                    if (string.IsNullOrWhiteSpace(url))
                    {
                        string LocalPath = txt5 + oldFile1.Replace("/", @"\");
                        string extension = Path.GetExtension(oldFile1).ToLower();
                        if (!File.Exists(LocalPath))
                        {
                            SetTextErrorMessage("文件不存在:" + LocalPath);
                            continue;
                        }
                        byte[] fileByte = File.ReadAllBytes(LocalPath);
                        if (fileByte.Length == 0)
                        {
                            SetTextErrorMessage("文件大小为空:" + LocalPath);
                            continue;
                        }
                        url = OssHelper.UploadFileFromByte(OssHelper.GetBucket(""), baseDir + oldFile1, fileByte, extension);
                    }

                    DataSet ds1 = DbHelperSQL.Query(
                        string.Format("SELECT 1 FROM {0} WHERE [TableKeyID]='{1}' AND [TableName]='{2}' AND [FieldName]='{3}' AND [OldPath]='{4}'"
                                      , "FileToOssLog", dr[txt4].ToString(), txt1, txt2, oldFile));

                    if (ds1 != null && ds1.Tables.Count != 0 && ds1.Tables[0].Rows.Count == 0)
                    {
                        sb.AppendFormat("INSERT INTO {0} ([TableKeyID],[TableName],[FieldName],[OldPath],[NewPath]) ", "FileToOssLog");
                        sb.AppendFormat("VALUES ('{0}','{1}','{2}','{3}','{4}') ;", dr[txt4].ToString(), txt1, txt2, oldFile, url);
                    }
                }
                catch (Exception ex)
                {
                    SetTextErrorMessage(ex.Message);
                }
                finally
                {
                    now++;
                    SetTextMessage();
                }
            }
            try
            {
                if (!string.IsNullOrWhiteSpace(sb.ToString()))
                {
                    DbHelperSQL.ExecuteSql(sb.ToString());
                }
            }
            catch (Exception ex)
            {
                SetTextErrorMessage(ex.Message);
            }
        }
예제 #6
0
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

            #region 检查是否登录

            currentUserInfo = bllWebsiteDomainInfo.GetCurrentUserInfo();
            if (currentUserInfo == null)
            {
                resp.Msg = "您还未登录";
                context.Response.Write(Common.JSONHelper.ObjectToJson(resp));
                return;
            }
            websiteOwner = bllWebsiteDomainInfo.WebsiteOwner;
            #endregion

            #region 检查文件
            //文件夹
            string fd = context.Request["fd"];
            if (string.IsNullOrWhiteSpace(fd))
            {
                fd = "audio";
            }

            //检查文件
            if (context.Request.Files.Count == 0)
            {
                resp.Msg = "请选择文件";
                context.Response.Write(Common.JSONHelper.ObjectToJson(resp));
                return;
            }

            string fileName      = context.Request.Files[0].FileName;
            string fileExtension = Path.GetExtension(fileName).ToLower();
            if (string.IsNullOrWhiteSpace(fileName))
            {
                resp.Msg = "请选择文件";
                context.Response.Write(Common.JSONHelper.ObjectToJson(resp));
                return;
            }
            //格式限制
            if (fileExtension != ".mp3")
            {
                resp.Msg = "为保障兼容请上传mp3文件";
                context.Response.Write(Common.JSONHelper.ObjectToJson(resp));
                return;
            }
            #endregion

            string filePath = "";
            try
            {
                filePath = OssHelper.UploadFile(OssHelper.GetBucket(websiteOwner), OssHelper.GetBaseDir(websiteOwner), currentUserInfo.UserID, "audio", context.Request.Files[0]);
            }
            catch (Exception ex)
            {
                resp.Msg = ex.Message;
                context.Response.Write(Common.JSONHelper.ObjectToJson(resp));
                return;
            }
            //返回字符串
            resp.IsSuccess = true;
            resp.ExStr     = filePath;
            resp.Msg       = "上传完成";
            context.Response.Write(Common.JSONHelper.ObjectToJson(resp));
        }
예제 #7
0
        public override void Process()
        {
            if (!string.IsNullOrWhiteSpace(UploadConfig.OssBucket))
            {
                #region 改Oss后方法
                var file = Request.Files[UploadConfig.UploadFieldName];
                Result.OriginFileName = file.FileName;
                try
                {
                    Result.Url   = OssHelper.UploadFile(OssHelper.GetBucket(UploadConfig.WebsiteOwner), OssHelper.GetBaseDir(UploadConfig.WebsiteOwner), UploadConfig.UserID, UploadConfig.FileType, file);
                    Result.State = UploadState.Success;
                }
                catch (Exception ex)
                {
                    Result.State        = UploadState.FileAccessError;
                    Result.ErrorMessage = ex.Message;
                }
                finally
                {
                    WriteResult();
                }
                #endregion
            }
            else
            {
                #region 改Oss前方法
                byte[] uploadFileBytes = null;
                string uploadFileName  = null;

                if (UploadConfig.Base64)
                {
                    uploadFileName  = UploadConfig.Base64Filename;
                    uploadFileBytes = Convert.FromBase64String(Request[UploadConfig.UploadFieldName]);
                }
                else
                {
                    var file = Request.Files[UploadConfig.UploadFieldName];
                    uploadFileName = file.FileName;

                    if (!CheckFileType(uploadFileName))
                    {
                        Result.State = UploadState.TypeNotAllow;
                        WriteResult();
                        return;
                    }
                    if (!CheckFileSize(file.ContentLength))
                    {
                        Result.State = UploadState.SizeLimitExceed;
                        WriteResult();
                        return;
                    }

                    uploadFileBytes = new byte[file.ContentLength];
                    try
                    {
                        file.InputStream.Read(uploadFileBytes, 0, file.ContentLength);
                    }
                    catch (Exception)
                    {
                        Result.State = UploadState.NetworkError;
                        WriteResult();
                    }
                }

                Result.OriginFileName = uploadFileName;

                var savePath  = PathFormatter.Format(uploadFileName, UploadConfig.PathFormat);
                var localPath = Server.MapPath(savePath);
                try
                {
                    if (!Directory.Exists(Path.GetDirectoryName(localPath)))
                    {
                        Directory.CreateDirectory(Path.GetDirectoryName(localPath));
                    }
                    File.WriteAllBytes(localPath, uploadFileBytes);
                    Result.Url   = savePath;
                    Result.State = UploadState.Success;
                }
                catch (Exception e)
                {
                    Result.State        = UploadState.FileAccessError;
                    Result.ErrorMessage = e.Message;
                }
                finally
                {
                    WriteResult();
                }
                #endregion
            }
        }