Example #1
0
        //上传文件
        public static string UpLoad(HtmlInputFile file, string saveFile)
        {
            //获取文件路径
            string fileName = file.PostedFile.FileName;
            //获取文件的后缀
            string extendName = fileName.Substring(fileName.LastIndexOf(".") + 1).ToLower();
            string newName    = null;

            //过滤文件的后缀
            if (extendName == "jpg" || extendName == "bmp" || extendName == "gif")
            {
                // int iSeed = 10;
                Random ro   = new Random(100);
                long   tick = DateTime.Now.Ticks;
                Random ran  = new Random((int)(tick & 0xffffffffL) | (int)(tick >> 32));

                int iResult;
                int iUp = 100;
                iResult = ro.Next(iUp);


                newName = System.Guid.NewGuid().ToString();
                file.PostedFile.SaveAs(saveFile + "/" + newName + "." + extendName);
            }
            return(newName + "." + extendName);
        }
        /// <summary>
        /// Adds file and upload area.
        /// </summary>
        private void AddFileAndUploadArea()
        {
            _pnlFile = new Panel {
                ID = "pnlFile", CssClass = "dnnFormItem"
            };

            _lblFile = new Label {
                ID = "lblFile", Visible = true
            };
            {
                _pnlFile.Controls.Add(_lblFile);
            }

            _cboFiles = new DnnComboBox {
                ID = "cboFile", CssClass = "wthCombobox", DataTextField = "Text", DataValueField = "Value", AutoPostBack = true
            };
            {
                _cboFiles.SelectedIndexChanged += FileChanged;
            }

            _pnlFile.Controls.Add(_cboFiles); _pnlLeftDiv.Controls.Add(_pnlFile);

            _pnlUpload = new Panel {
                ID = "pnlUpload", CssClass = "dnnFormItem", Visible = true
            };

            _txtFile = new HtmlInputFile();
            {
                _txtFile.Attributes.Add("size", "13"); _pnlUpload.Controls.Add(_txtFile);
            }

            _pnlLeftDiv.Controls.Add(_pnlUpload);
        }
Example #3
0
        /// <summary>
        /// 保存文件
        /// </summary>
        /// <param name="fpath">全路径,Server.MapPath()</param>
        /// <param name="myFileUpload">上传控件</param>
        /// <returns></returns>
        public static string PhotoSaveinput(string fpath, HtmlInputFile myFileUpload)
        {
            string s           = "";
            string fileExtends = "";
            string fileName    = myFileUpload.PostedFile.FileName;

            if (fileName != "")
            {
                //取得文件后缀
                fileExtends = GetFileExtends(fileName);
                if (!CheckFileExtends(fileExtends))
                {
                    return("格式错误");
                }
                //1m图片
                if (myFileUpload.PostedFile.ContentLength >= 1024 * 1024)
                {
                    return("超过大小");
                }

                Random rd = new Random();
                s = DateTime.Now.ToFileTimeUtc() + "." + fileExtends;
                string file = fpath + "\\" + s;
                try
                {
                    myFileUpload.PostedFile.SaveAs(file);
                }
                catch (Exception ee)
                {
                    throw new Exception(ee.ToString());
                }
            }
            return(s);
        }
Example #4
0
        public static bool SaveAccessory(this HtmlInputFile inputFile, string uploadDirectory, int limitSize, string fileName)
        {
            string str = inputFile.PostedFile.FileName;

            uploadDirectory = HttpContext.Current.Server.MapPath("./") + uploadDirectory;
            if (inputFile.PostedFile.ContentLength > limitSize)
            {
                HttpContext.Current.Response.Write("<script language=javascript>alert('上传文件限制最大为" + Convert.ToString((int)(limitSize / 0x400)) + "k');history.back(-1);</script>");
                HttpContext.Current.Response.End();
                return(false);
            }
            if (str.Trim().Length > 0)
            {
                if (!Directory.Exists(uploadDirectory))
                {
                    Directory.CreateDirectory(uploadDirectory);
                }
                fileName = uploadDirectory + fileName;
                try
                {
                    inputFile.PostedFile.SaveAs(fileName);
                    return(true);
                }
                catch (Exception)
                {
                    return(false);
                }
            }
            return(false);
        }
Example #5
0
        /// <summary>
        /// 上传Word文档
        /// </summary>
        /// <param name="inputFile"></param>
        /// <param name="filePath"></param>
        private string UpLoadFile(HtmlInputFile inputFile)
        {
            string fileName, fileExtension;

            //建立上传对象
            HttpPostedFile postedFile = inputFile.PostedFile;

            fileName      = System.IO.Path.GetFileName(postedFile.FileName);
            fileExtension = System.IO.Path.GetExtension(fileName);

            string phyPath = Server.MapPath("~/") + "Portals\\0\\WordImport\\";

            //判断路径是否存在,若不存在则创建路径

            DirectoryInfo upDir = new DirectoryInfo(phyPath);

            if (!upDir.Exists)
            {
                upDir.Create();
            }

            //保存文件
            try
            {
                postedFile.SaveAs(phyPath + fileName);
            }
            catch
            {
            }
            return(phyPath + fileName);
        }
        private bool UploadFile(string sFileName, HtmlInputFile httpFile)
        {
            Stream oStream;
            int    FileLen;
            string strReturn = "";
            bool   bolResult = false;

            CBSolutions.ETH.Web.WebRefNew.DownloadNew objService2 = new CBSolutions.ETH.Web.WebRefNew.DownloadNew();
            objService2.Url = GetURL2();

            try
            {
                FileLen = httpFile.PostedFile.ContentLength;
                byte[] oFileByte = new byte[FileLen];
                oStream = httpFile.PostedFile.InputStream;
                oStream.Read(oFileByte, 0, FileLen);
                bolResult = objService2.UploadFileNew(sFileName, oFileByte, strReturn, strChildBuyer);
                if (bolResult == false)
                {
                    throw new Exception(strReturn);
                }
            }
            catch (Exception ex)
            {
                string ss = ex.Message;
            }
            finally
            {
                objService2 = null;
            }
            return(bolResult);
        }
Example #7
0
        public static bool SaveAccessory(this HtmlInputFile inputFile, string uploadDirectory, int limitSize, out string fileGuidName)
        {
            string fileName = inputFile.PostedFile.FileName;
            string str2     = string.Empty;

            fileGuidName = string.Empty;
            if (inputFile.PostedFile.ContentLength > limitSize)
            {
                HttpContext.Current.Response.Write("<script language=javascript>alert('上传文件限制最大为" + Convert.ToString((int)(limitSize / 0x400)) + "k');history.back(-1);</script>");
                HttpContext.Current.Response.End();
                return(false);
            }
            if (fileName.Trim().Length > 0)
            {
                str2 = Guid.NewGuid().ToString() + "." + fileName.GetFileExtension();
                if (!Directory.Exists(uploadDirectory))
                {
                    Directory.CreateDirectory(uploadDirectory);
                }
                string filename = uploadDirectory + str2;
                try
                {
                    inputFile.PostedFile.SaveAs(filename);
                    fileGuidName = str2;
                    return(true);
                }
                catch (Exception)
                {
                    return(false);
                }
            }
            return(false);
        }
Example #8
0
        private void SaveAttachment(object messageID, HtmlInputFile file)
        {
            if (file.PostedFile == null || file.PostedFile.FileName.Trim().Length == 0 || file.PostedFile.ContentLength == 0)
            {
                return;
            }

            string sUpDir   = Request.MapPath(Config.ConfigSection["uploaddir"]);
            string filename = file.PostedFile.FileName;

            int pos = filename.LastIndexOfAny(new char[] { '/', '\\' });

            if (pos >= 0)
            {
                filename = filename.Substring(pos + 1);
            }

            // verify the size of the attachment
            if (BoardSettings.MaxFileSize > 0 && file.PostedFile.ContentLength > BoardSettings.MaxFileSize)
            {
                throw new Exception(GetText("ERROR_TOOBIG"));
            }

            if (BoardSettings.UseFileTable)
            {
                DB.attachment_save(messageID, filename, file.PostedFile.ContentLength, file.PostedFile.ContentType, file.PostedFile.InputStream);
            }
            else
            {
                file.PostedFile.SaveAs(String.Format("{0}{1}.{2}", sUpDir, messageID, filename));
                DB.attachment_save(messageID, filename, file.PostedFile.ContentLength, file.PostedFile.ContentType, null);
            }
        }
Example #9
0
        private void CheckValidFile(HtmlInputFile file)
        {
            if (file.PostedFile == null || file.PostedFile.FileName.Trim().Length == 0 || file.PostedFile.ContentLength == 0)
            {
                return;
            }

            string filename = file.PostedFile.FileName;
            int    pos      = filename.LastIndexOfAny(new char[] { '/', '\\' });

            if (pos >= 0)
            {
                filename = filename.Substring(pos + 1);
            }
            pos = filename.LastIndexOf('.');
            if (pos >= 0)
            {
                switch (filename.Substring(pos + 1).ToLower())
                {
                default:
                    break;

                case "asp":
                case "aspx":
                case "ascx":
                case "config":
                case "php":
                case "php3":
                case "js":
                case "vb":
                case "vbs":
                    throw new Exception(String.Format(GetText("fileerror"), filename));
                }
            }
        }
Example #10
0
        /// <summary>
        /// 上传Word文档
        /// </summary>
        /// <param name="inputFile"></param>
        /// <param name="filePath"></param>
        private string UpLoadFile(HtmlInputFile inputFile)
        {
            string fileName, fileExtension;

            //建立上传对象
            HttpPostedFile postedFile = inputFile.PostedFile;

            fileName      = System.IO.Path.GetFileName(postedFile.FileName);
            fileExtension = System.IO.Path.GetExtension(fileName);

            //上传图片保存Base路径 如果修改此路径需要同时修改图片地址替换路径(在212行附件)
            string phyPath = Server.MapPath("~/") + "FckUpload\\ImportWord\\0\\";

            //判断路径是否存在,若不存在则创建路径
            DirectoryInfo upDir = new DirectoryInfo(phyPath);

            if (!upDir.Exists)
            {
                upDir.Create();
            }

            //保存文件
            try
            {
                postedFile.SaveAs(phyPath + fileName);
            }
            catch
            {
            }
            return(phyPath + fileName);
        }
Example #11
0
    public void Upload(HtmlInputFile fname, string fpath)
    {
        string serverfilename;

        //string err ;
        try
        {
            serverfilename = Path.GetFileName(fname.PostedFile.FileName);
            // Do While File.Exists(fpath & serverfilename)

            //serverfilename = Trim("1") & serverfilename
            //								 Loop
            fname.PostedFile.SaveAs(fpath + serverfilename);
            //===============================================================================================
            //ImageResize IR=new ImageResize ();
            //IR.imgResize(fpath,serverfilename);
            //IR.ImgRes (fpath + serverfilename);
            ///==============================================================================================
            ///==============================================================================================


            ///===============================================================================================
        }

        catch (Exception e)
        {
        }
    }
Example #12
0
        public static int UploadFile(Page page, HtmlInputFile file, string TargetDirectory, ref string NewFileName, string LimitFileTypeList)
        {
            if (!m000001(file, LimitFileTypeList))
            {
                return(-101);
            }
            if (file.Value.Trim() == "")
            {
                return(-1);
            }
            if (!TargetDirectory.EndsWith("/") && !TargetDirectory.EndsWith(@"\"))
            {
                TargetDirectory = TargetDirectory + "/";
            }
            string extension = Path.GetExtension(file.Value);

            NewFileName = GetNewFileName(page, TargetDirectory, extension, "");
            try
            {
                file.PostedFile.SaveAs(page.Server.MapPath(TargetDirectory + NewFileName));
            }
            catch
            {
                return(-3);
            }
            return(0);
        }
        public string[] CreateSharing(HtmlInputFile oFile, string clientIp, string pw, TextBox eMail = null, TextBox comment = null)
        {
            if (pw != "123")
            {
                return(new string[] { "Wrong password! Access denied.", "" });
            }
            string resString;
            string sharingLink = UploadFile(oFile);

            resString = sharingLink;
            if (eMail.Text != "" && sharingLink.StartsWith("http"))
            {
                string mailResult = SentMail(eMail, comment, sharingLink);
                resString = $"Sharing link: {sharingLink}  " + $"Sent mail result: {mailResult}";
            }

            LogInfo loginfo = new LogInfo {
                sharingLink      = sharingLink,
                uploadedFileName = oFile.PostedFile.FileName,
                ipAddress        = clientIp,
                eMail            = eMail.Text,
                uploadDate       = globalUploadedDate,
                uploadedTime     = globalUploadedTime
            };
            string logFilePath = WriteLogInformation(loginfo);

            return(new string[] { resString, logFilePath });
        }
Example #14
0
        //上传图片
        public static string UPimg(string fname, HtmlInputFile fn, string path)
        {
            if (fn == null)
            {
                return(null);
            }
            UploadImg upload = new UploadImg();

            upload.FormFile = fn;
            upload.SavePath = path;
            //upload.IsCreateImg = true;
            //upload.IsDraw = true;
            //upload.DrawStyle = 0;
            //if (!String.IsNullOrEmpty(fname))
            //{
            //    upload.OutFileName = fname;
            //}
            upload.Open();
            if (upload.Error.ToString() == "0")
            {
                return(upload.OutFileName);
            }
            else
            {
                return("");
            }
        }
Example #15
0
    protected string UploadFile(HtmlInputFile InputFile)
    {
        string ret         = "fail";
        string uploadName  = InputFile.Value;                         //获取待上传图片的完整路径,包括文件名
        string pictureName = DateTime.Now.ToString("yyyyMMddHHmmss"); //上传后的图片名,以当前时间为文件名,确保文件名没有重复

        if (InputFile.Value != "")
        {
            int    idx    = uploadName.LastIndexOf(".");
            string suffix = uploadName.Substring(idx);//获得上传的图片的后缀名
            pictureName = pictureName + suffix;
        }
        try
        {
            if (uploadName != "")
            {
                string path = Server.MapPath("~/ClientWeb/upload/UpLoadFile/");
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                InputFile.PostedFile.SaveAs(path + pictureName);
                ret = pictureName;
            }
        }
        catch (Exception ex)
        {
        }
        return(ret);
    }
Example #16
0
        ///<summary>
        ///是否允许该扩展名上传
        ///</summary>
        ///<paramname = "hifile">HtmlInputFile控件</param>
        ///<returns>允许则返回true,否则返回false</returns>
        public static bool IsAllowedExtension(HtmlInputFile hifile)
        {
            string strOldFilePath = "";
            string strExtension   = "";

            //允许上传的扩展名,可以改成从配置文件中读出
            //string[]arrExtension = {".gif",".jpg",".jpeg",".bmp",".png",".xls",".csv"};
            string[] arrExtension = { ".xls", ".xlsx", ".csv", ".txt", ".doc", ".docx", ".pdf", ".jpg", ".bmp" };

            if (hifile.PostedFile.FileName != string.Empty)
            {
                strOldFilePath = hifile.PostedFile.FileName;
                //取得上传文件的扩展名
                strExtension = strOldFilePath.Substring(strOldFilePath.LastIndexOf("."));
                //判断该扩展名是否合法
                for (int i = 0; i < arrExtension.Length; i++)
                {
                    if (strExtension.ToUpper().Equals(arrExtension[i].ToUpper()))
                    {
                        return(true);
                    }
                }
            }
            return(false);
        }
Example #17
0
        /// <summary>
        /// 校验上传的文件类型
        /// </summary>
        /// <param name="file"></param>
        /// <param name="LimitFileTypeList"></param>
        /// <returns></returns>
        private static bool ValidFileType(HtmlInputFile file, string LimitFileTypeList)
        {
            if (String.IsNullOrEmpty(LimitFileTypeList))
            {
                return(true);
            }

            string ContentType = file.PostedFile.ContentType.ToLower();

            LimitFileTypeList = LimitFileTypeList.Trim().ToLower();
            string[] strs = LimitFileTypeList.Split(',');

            foreach (string str in strs)
            {
                if (String.IsNullOrEmpty(str))
                {
                    continue;
                }

                string t = str.Trim();

                if (ContentType.IndexOf(t) >= 0)
                {
                    return(true);
                }
            }

            return(false);
        }
Example #18
0
        /// <summary>
        /// Check to see if the user is trying to upload a valid file.
        /// </summary>
        /// <param name="uploadedFile">
        /// the uploaded file.
        /// </param>
        /// <returns>
        /// true if file is valid for uploading. otherwise false.
        /// </returns>
        private bool CheckValidFile([NotNull] HtmlInputFile uploadedFile)
        {
            string filePath = uploadedFile.PostedFile.FileName.Trim();

            if (filePath.IsNotSet() || uploadedFile.PostedFile.ContentLength == 0)
            {
                return(false);
            }

            string extension = Path.GetExtension(filePath).ToLower();

            // remove the "period"
            extension = extension.Replace(".", string.Empty);
            string[] aImageExtensions = { "jpg", "gif", "png", "bmp" };

            // If we don't get a match from the db, then the extension is not allowed
            DataTable dt = this.GetRepository <FileExtension>().List(extension);

            // also, check to see an image is being uploaded.
            if (Array.IndexOf(aImageExtensions, extension) == -1 || dt.Rows.Count == 0)
            {
                this.PageContext.AddLoadMessage(this.GetTextFormatted("FILEERROR", extension));
                return(false);
            }

            return(true);
        }
 private ImageContract loadImage(HtmlInputFile imageControl, int profileID)
 {
     byte[] data;
     if (imageControl.PostedFile.InputStream.Length > 0)
     {
         using (Stream inputStream = imageControl.PostedFile.InputStream)
         {
             MemoryStream memoryStream = inputStream as MemoryStream;
             if (memoryStream == null)
             {
                 memoryStream = new MemoryStream();
                 inputStream.CopyTo(memoryStream);
             }
             data = memoryStream.ToArray();
         }
         return(new ImageContract()
         {
             Name = imageControl.Value,
             FileData = data,
             ProfileID = profileID
         });
     }
     else
     {
         return(null);
     }
 }
Example #20
0
        /// <summary>
        ///   AddFileRow adds the Files Row
        /// </summary>
        private void AddFileAndUploadArea()
        {
            //Create Url Div
            _pnlFile = new Panel {
                CssClass = "dnnFormItem"
            };

            //Create File Label
            _lblFile = new Label {
                EnableViewState = false
            };
            _pnlFile.Controls.Add(_lblFile);

            //Create Files Combo
            _cboFiles = new DropDownList {
                ID = "File", DataTextField = "Text", DataValueField = "Value", AutoPostBack = true
            };
            _cboFiles.SelectedIndexChanged += FileChanged;
            _pnlFile.Controls.Add(_cboFiles);

            _pnlLeftDiv.Controls.Add(_pnlFile);

            //Create Upload Div
            _pnlUpload = new Panel {
                CssClass = "dnnFormItem"
            };

            //Create Upload Box
            _txtFile = new HtmlInputFile();
            _txtFile.Attributes.Add("size", "13");
            _pnlUpload.Controls.Add(_txtFile);

            _pnlLeftDiv.Controls.Add(_pnlUpload);
        }
Example #21
0
        private static string uperror(HtmlInputFile ControlId, float FileSize)
        {
            string output   = "";
            string filename = ControlId.PostedFile.FileName;

            if (filename == "")
            {
                output = "请选择图片...";
            }
            else
            {
                float FileLength = float.Parse((float.Parse(ControlId.PostedFile.ContentLength.ToString()) / 1024 / 1024).ToString("#0.00"));
                if (FileLength > FileSize)
                {
                    output = "文件大小不得超过" + FileSize + "M" + "<font style=\"color:#000;\">(&nbsp;当前文件大小约为&nbsp;" + FileLength + "M&nbsp;)</font>";
                }
                FileExtension[] fe = { FileExtension.GIF, FileExtension.JPG, FileExtension.BMP };
                if (!FileValidation.IsAllowedExtension(ControlId, fe))
                {
                    string style = FileNodeName(fe);
                    output = "只支持" + style + "格式图片";
                }
                else
                {
                    output = "";
                }
            }
            return(output);
        }
Example #22
0
            public static bool IsAllowedExtension(HtmlInputFile fu, FileExtension[] fileEx)
            {
                int fileLen = fu.PostedFile.ContentLength;

                byte[] imgArray = new byte[fileLen];
                fu.PostedFile.InputStream.Read(imgArray, 0, fileLen);
                MemoryStream ms = new MemoryStream(imgArray);

                System.IO.BinaryReader br = new System.IO.BinaryReader(ms);
                string fileclass          = "";
                byte   buffer;

                try
                {
                    buffer     = br.ReadByte();
                    fileclass  = buffer.ToString();
                    buffer     = br.ReadByte();
                    fileclass += buffer.ToString();
                }
                catch
                {
                }
                br.Close();
                ms.Close();
                foreach (FileExtension fe in fileEx)
                {
                    if (Int32.Parse(fileclass) == (int)fe)
                    {
                        return(true);
                    }
                }
                return(false);
            }
Example #23
0
        public static bool CreateNewUserApp(UserApplication newUser, HtmlInputFile imageUploader)
        {
            string applicationName = newUser.AppName;
            string username        = newUser.UserName;
            string password        = newUser.Password;

            string[] userRoles        = newUser.UserRoles.ToArray();
            bool     isNewUserCreated = false;

            Membership.ApplicationName = applicationName;
            Roles.ApplicationName      = applicationName;

            Membership.CreateUser(username, password);

            if (Membership.ValidateUser(username, password))
            {
                Roles.AddUserToRoles(username, userRoles);

                string profileImageVersion = UploadCloudinaryProfileImage(imageUploader, applicationName, username);

                Membership.ApplicationName = applicationName;
                MembershipUser currentUser = Membership.GetUser(username);
                currentUser.Comment = profileImageVersion;
                Membership.UpdateUser(currentUser);
                Membership.ApplicationName = "ShopHelperAsp";

                isNewUserCreated = true;
            }
            Membership.ApplicationName = "ShopHelperAsp";
            Roles.ApplicationName      = "ShopHelperAsp";

            return(isNewUserCreated);
        }
Example #24
0
        public void InstantiateIn(Control objCntrl)
        {
            HtmlInputFile hFile = new HtmlInputFile();

            hFile.DataBinding += new EventHandler(hFile_DataBinding);
            objCntrl.Controls.Add(hFile);
        }
Example #25
0
        /// <summary>
        /// Check to see if the user is trying to upload a valid file.
        /// </summary>
        /// <param name="uploadedFile">
        /// the uploaded file.
        /// </param>
        /// <returns>
        /// true if file is valid for uploading. otherwise false.
        /// </returns>
        private bool CheckValidFile([NotNull] HtmlInputFile uploadedFile)
        {
            var filePath = uploadedFile.PostedFile.FileName.Trim();

            if (filePath.IsNotSet() || uploadedFile.PostedFile.ContentLength == 0)
            {
                return(false);
            }

            if (uploadedFile.PostedFile.ContentType.ToLower().Contains("text"))
            {
                return(false);
            }

            var extension = Path.GetExtension(filePath).ToLower();

            // remove the "period"
            extension = extension.Replace(".", string.Empty);
            string[] imageExtensions = { "jpg", "gif", "png", "bmp" };

            // If we don't get a match from the db, then the extension is not allowed
            // also, check to see an image is being uploaded.
            if (Array.IndexOf(imageExtensions, extension) == -1 || this.GetRepository <FileExtension>()
                .Get(e => e.BoardId == this.PageContext.PageBoardID && e.Extension == extension).Count == 0)
            {
                this.PageContext.AddLoadMessage(this.GetTextFormatted("FILEERROR", extension));
                return(false);
            }

            return(true);
        }
Example #26
0
        //检查文件名中是否包含非法字符 # @ . ~
        public static bool IsAllowString(HtmlInputFile hifile)
        {
            string strOldFilePath = "";
            string strExtension   = "";

            string[] arrExtension = { "#", "@", ".", "~", "`", "\\", "!", "'", "#" };

            bool returnvalue = true;

            if (hifile.PostedFile.FileName != string.Empty)
            {
                strOldFilePath = hifile.PostedFile.FileName;
                //取得上传文件名

                strExtension = strOldFilePath.Substring(0, strOldFilePath.LastIndexOf("."));

                strExtension = strExtension.Substring(strExtension.LastIndexOf("\\") + 1);

                //strExtension = strOldFilePath.Substring(strOldFilePath.LastIndexOf("."));
                //判断该扩展名是否合法
                for (int i = 0; i < arrExtension.Length; i++)
                {
                    if (strExtension.IndexOf(arrExtension[i].ToUpper()) >= 0)
                    {
                        return(false);
                    }
                }
            }
            return(returnvalue);
        }
Example #27
0
        /// <summary>
        /// 上传文件,按指定的文件名 FileName 保存
        /// </summary>
        /// <param name="page">输入this.Page即可</param>
        /// <param name="file">file 控件名称</param>
        /// <param name="TargetDirectory">上传服务器上哪个目录(相对目录,如:../Images/)</param>
        /// <param name="FileName">指定的保存为...文件名</param>
        /// <param name="OverwriteExistFile">是否覆盖同名文件</param>
        /// <param name="LimitFileTypeList">限制的文件类型列表,如:image, text</param>
        /// <returns>返回:	-1 没有选择文件 -2 OverwriteExistFile = false, 不覆盖已有文件时,文件已经存在; -3 上传错误; 0 OK</returns>
        public static int UploadFile(Page page, HtmlInputFile file, string TargetDirectory, string FileName, bool OverwriteExistFile, string LimitFileTypeList)
        {
            if (!ValidFileType(file, LimitFileTypeList))
            {
                return(-101);
            }

            if (file.Value.Trim() == "")
            {
                return(-1);
            }

            if (!TargetDirectory.EndsWith("/") && !TargetDirectory.EndsWith("\\"))
            {
                TargetDirectory += "/";
            }

            string TargetFileName = page.Server.MapPath(TargetDirectory + FileName);

            if (System.IO.File.Exists(TargetFileName) && (!OverwriteExistFile))
            {
                return(-2);
            }

            try
            {
                file.PostedFile.SaveAs(TargetFileName);
            }
            catch
            {
                return(-3);
            }

            return(0);
        }
Example #28
0
        /// <summary>
        /// 上传文件,返回新 保存的 NewFileName 文件名
        /// </summary>
        /// <param name="page">输入this.Page即可</param>
        /// <param name="file">file 控件名称</param>
        /// <param name="TargetDirectory">上传服务器上哪个目录(相对目录,如:../Images/)</param>
        /// <param name="NewFileName">返回服务器目录下生成的新文件名称</param>
        /// <param name="LimitFileTypeList">限制的文件类型列表,如:image, text</param>
        /// <returns>返回:	-1 没有选择文件  -3 上传错误; 0 OK</returns>
        public static int UploadFile(Page page, HtmlInputFile file, string TargetDirectory, ref string NewFileName, string LimitFileTypeList)
        {
            if (!ValidFileType(file, LimitFileTypeList))
            {
                return(-101);
            }

            if (file.Value.Trim() == "")
            {
                return(-1);
            }

            if (!TargetDirectory.EndsWith("/") && !TargetDirectory.EndsWith("\\"))
            {
                TargetDirectory += "/";
            }

            string Ext = System.IO.Path.GetExtension(file.Value);

            NewFileName = GetNewFileName(page, TargetDirectory, Ext, "");       //Flag 前缀

            try
            {
                file.PostedFile.SaveAs(page.Server.MapPath(TargetDirectory + NewFileName));
            }
            catch
            {
                return(-3);
            }

            return(0);
        }
Example #29
0
        public static int UploadFile(Page page, HtmlInputFile file, string TargetDirectory, ref string ShortFileName, bool OverwriteExistFile, string LimitFileTypeList)
        {
            string str2;

            if (!m000001(file, LimitFileTypeList))
            {
                return(-101);
            }
            try
            {
                string str = file.Value.Trim().Replace(@"\", @"\\");
                str2          = str.Substring(str.LastIndexOf(@"\") + 1, (str.Length - str.LastIndexOf(@"\")) - 1);
                ShortFileName = str2;
            }
            catch
            {
                return(-1);
            }
            string path = page.Server.MapPath(TargetDirectory + str2);

            if (System.IO.File.Exists(path) && !OverwriteExistFile)
            {
                return(-2);
            }
            try
            {
                file.PostedFile.SaveAs(path);
            }
            catch
            {
                return(-3);
            }
            return(0);
        }
Example #30
0
        public string GetUpLoadFile(HtmlInputFile FilePicName, string FilePicPath, int FileSize)
        {
            if ((FileSize != 0) && (FilePicName.PostedFile.ContentLength > (FileSize * 0x400)))
            {
                HttpContext.Current.Response.Write("<script>alert('文件大小超出!');window.close();</script>");
                HttpContext.Current.Response.End();
            }
            switch (Path.GetFileName(FilePicName.PostedFile.FileName))
            {
            case "":
            case null:
                HttpContext.Current.Response.Write("<script language=javascript>alert('文件名不能为空!');window.close();</script>");
                HttpContext.Current.Response.End();
                break;
            }
            if ((((((FilePicName.PostedFile.ContentType != "image/gif") && (FilePicName.PostedFile.ContentType != "image/pjpeg")) && ((FilePicName.PostedFile.ContentType != "image/bmp") && (FilePicName.PostedFile.ContentType != "image/x-png"))) && (((FilePicName.PostedFile.ContentType != "image/jpeg") && (FilePicName.PostedFile.ContentType != "application/x-shockwave-flash")) && ((FilePicName.PostedFile.ContentType != "application/vnd.ms-excel") && (FilePicName.PostedFile.ContentType != "application/msword")))) && ((((FilePicName.PostedFile.ContentType != "application/vnd.ms-powerpoint") && (FilePicName.PostedFile.ContentType != "application/octet-stream")) && ((FilePicName.PostedFile.ContentType != "application/x-zip-compressed") && (FilePicName.PostedFile.ContentType != "pplication/vnd.rn-realmedia"))) && (((FilePicName.PostedFile.ContentType != "application/vnd.rn-realmedia-vbr") && (FilePicName.PostedFile.ContentType != "video/x-ms-wmv")) && ((FilePicName.PostedFile.ContentType != "audio/x-ms-wma") && (FilePicName.PostedFile.ContentType != "video/x-ms-asf"))))) && ((((FilePicName.PostedFile.ContentType != "video/avi") && (FilePicName.PostedFile.ContentType != "audio/mp3")) && ((FilePicName.PostedFile.ContentType != "video/mpeg4") && (FilePicName.PostedFile.ContentType != "video/mpg"))) && (((FilePicName.PostedFile.ContentType != "audio/mid") && (FilePicName.PostedFile.ContentType != "video/avi")) && ((FilePicName.PostedFile.ContentType != "application/x-rar-compressed") && (FilePicName.PostedFile.ContentType != "application/x-zip-compressed")))))
            {
                HttpContext.Current.Response.Write("<script>alert('文件类型不是允许上传的类型');window.close();</script>");
                HttpContext.Current.Response.End();
                return("");
            }
            string extension = Path.GetExtension(FilePicName.PostedFile.FileName);
            string fileName  = function.GetFileName();
            string str4      = DateTime.Now.ToString("yyyyMM");
            string path      = HttpContext.Current.Server.MapPath(FilePicPath) + str4 + "/";

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            string filename = path + fileName + extension;

            FilePicName.PostedFile.SaveAs(filename);
            return(str4 + "/" + fileName + extension);
        }
Example #31
0
    public static String filePost(HtmlInputFile fileLoadimgTop , String paths )
    {
        paths=  paths.Replace("/","");
         /// paths = Server.MapPath("\\images") ;
        if (fileLoadimgTop != null && fileLoadimgTop.PostedFile != null && fileLoadimgTop.PostedFile.FileName != "")
        {
            //try
            //{
            //  ///  string path = Request.MapPath("images");

                fileLoadimgTop.PostedFile.SaveAs( paths + "\\" + fileLoadimgTop.PostedFile.FileName);
                //Span1.InnerHtml = "File uploaded successfully to <b>c:\\temp\\" +
                //                  fileLoad.PostedFile.FileName + "</b> on the Web server";

             //   image = "~\\" + path + "\\" + fileLoadimgTop.PostedFile.FileName;

                image =  paths + "\\" + fileLoadimgTop.PostedFile.FileName;

            //}
            //catch (Exception exc)
            //{
            //    //Span1.InnerHtml = "Error saving file <b>c:\\temp\\" +
            //    //                fileLoad.PostedFile.FileName + "</b><br>" + exc.ToString();
            //}

        }

        return image;
    }
    // Demo - by Silv
    private string UploadFile2(HtmlInputFile objInput, string UploadType)
    {
        bool isFile = false;
        bool isSize = false;
        string sFileName = FileUpload.GetFileName(objInput.PostedFile);
        string sFileExtension = FileUpload.GetFileExtension(objInput.PostedFile);
        isFile = FileUpload.checkExtension(sFileName);
        if (isFile)
        {
            // File is OK And Check File Size
            isSize = FileUpload.checkFileSize(objInput.PostedFile, Constants.FILE_LIMIT_SIZE);
            if (isSize)
            {
                // Size is OK and Upload to server
                string sMapPath = System.Web.HttpContext.Current.Request.MapPath("");
                string sSavingFolder = "";

                switch (UploadType)
                {

                    case "productimg":
                        string sFolderProduct = Constants.SLASH + Constants.IMAGE_PRODUCTIMAGE_UPLOAD;
                        sSavingFolder = sFolderProduct + HttpContext.Current.Session[Constants.SESSION_PRODUCTID] + "/";
                        break;

                }

                string sFileUploaded = FileUpload.UploadImageToServer(sMapPath, objInput.PostedFile, sFileExtension, sSavingFolder);
                if (sFileUploaded != "")
                {
                    // File uploaded
                    sFileName = sFileUploaded;
                }
                else sFileName = "";
            }
        }

        return sFileName;
    }
Example #33
0
    public static string UploadFile(HtmlInputFile objInput, string UploadType)
    {
        bool isFile = false;
        bool isSize = false;
        string sFileName = FileUpload.GetFileName(objInput.PostedFile);
        string sFileExtension = FileUpload.GetFileExtension(objInput.PostedFile);

        isFile = FileUpload.checkExtension(sFileName);
        if (isFile)
        {
            // File is OK And Check File Size
            isSize = FileUpload.checkFileSize(objInput.PostedFile, Constants.FILE_LIMIT_SIZE);
            if (isSize)
            {
                // Size is OK and Upload to server
                string sMapPath =  System.Web.HttpContext.Current.Request.MapPath("");
                string sSavingFolder = "";

                switch (UploadType)
                {
                    case "image":
                        sSavingFolder = Constants.SLASH + Constants.IMAGE_NEWS_DEFAULT_UPLOAD;
                        break;
                    case "file":
                        sSavingFolder = Constants.SLASH + Constants.FILE_DEFAULT_UPLOAD;
                        break;
                    case "trademark":
                        sSavingFolder = Constants.SLASH + Constants.IMAGE_TRADEMARK_DEFAULT_UPLOAD;
                        break;
                    case "banner":
                        sSavingFolder = Constants.SLASH + Constants.IMAGE_BANNER_DEFAULT_UPLOAD;
                        break;
                    case "product":
                        sSavingFolder = Constants.SLASH + Constants.IMAGE_PRODUCT_DEFAULT_UPLOAD;
                        break;
                    case "productfile":
                        sSavingFolder = Constants.SLASH + Constants.PRODUCT_FILE;
                        break;
                    case "productimg":
                        string sFolderProduct = Constants.SLASH + Constants.IMAGE_PRODUCTIMAGE_UPLOAD;
                        sSavingFolder = sFolderProduct + HttpContext.Current.Session[Constants.SESSION_PRODUCTID] + "/";
                        break;
                    case "adv":
                        sSavingFolder = Constants.SLASH + Constants.IMAGE_ADV_DEFAULT_UPLOAD ;
                        break;
                    case "gallery":
                        sSavingFolder = Constants.SLASH + Constants.IMAGE_GALLERY_DEFAULT_UPLOAD;
                        break;
                    case "tourdestination":
                        sSavingFolder = Constants.SLASH + Constants.IMAGE_TOURDESTINATION_UPLOAD;
                        break;

                    case "gallerydetail":
                       string sFolder = Constants.SLASH + Constants.IMAGE_GALLERY_DEFAULT_UPLOAD;
                       sSavingFolder = sFolder + HttpContext.Current.Session[Constants.SESSION_GALLERYID] + "/";
                        break;
                    case "staticpage":
                        sSavingFolder = Constants.SLASH + Constants.IMAGE_STATICPAGE_DEFAULT_UPLOAD ;
                        break;
                    case "price":
                        sSavingFolder = Constants.SLASH + Constants.FILE_PRICE_DEFAULT_UPLOAD;
                        break;

                    case "testimonial":
                        sSavingFolder = Constants.SLASH + Constants.IMAGE_TESTIMONIAL_DEFAULT_UPLOAD;
                        break;

                    case "delivery":
                        sSavingFolder = Constants.SLASH + Constants.IMAGE_DELIVERY_UPLOAD;
                        break;
                    case "fileyc":
                        sSavingFolder = Constants.SLASH + Constants.FILE_NGUOI_DUNG;
                        break;
                }

                string sFileUploaded = FileUpload.UploadImageToServer(sMapPath, objInput.PostedFile, sFileExtension, sSavingFolder);
                if (sFileUploaded != "")
                {
                    // File uploaded
                    sFileName = sFileUploaded;
                }
                else sFileName = "";
            }
        }

        return sFileName;
    }
Example #34
0
    public FileUpLoad UpLoadFile(HtmlInputFile InputFile, string filePath, string myfileName, bool isRandom)
    {
        FileUpLoad fp = new FileUpLoad();
        string fileName, fileExtension;
        string saveName;

        //
        //建立上传对象
        //
        HttpPostedFile postedFile = InputFile.PostedFile;

        fileName = System.IO.Path.GetFileName(postedFile.FileName);
        fileExtension = System.IO.Path.GetExtension(fileName);

        //
        //根据类型确定文件格式
        //
        string format = "xlsx";

        //
        //如果格式都不符合则返回
        //
        if (format.IndexOf(fileExtension) == -1)
        {
            throw new ApplicationException("上传数据格式不合法");
        }

        //
        //根据日期和随机数生成随机的文件名
        //
        if (myfileName != string.Empty)
        {
            fileName = myfileName;
        }

        if (isRandom)
        {
            Random objRand = new Random();
            System.DateTime date = DateTime.Now;
            //生成随机文件名
            saveName = date.Year.ToString() + date.Month.ToString() + date.Day.ToString() + date.Hour.ToString() + date.Minute.ToString() + date.Second.ToString() + Convert.ToString(objRand.Next(99) * 97 + 100);
            fileName = saveName + fileExtension;
        }

        string phyPath = HttpContext.Current.Request.MapPath(filePath);

        //判断路径是否存在,若不存在则创建路径
        DirectoryInfo upDir = new DirectoryInfo(phyPath);
        if (!upDir.Exists)
        {
            upDir.Create();
        }

        //
        //保存文件
        //
        try
        {
            postedFile.SaveAs(phyPath + fileName);

            fp.FilePath = filePath + fileName;
            fp.FileExtension = fileExtension;
            fp.FileName = fileName;
        }
        catch
        {
            throw new ApplicationException("上传失败!");
        }

        //返回上传文件的信息
        return fp;
    }
Example #35
0
    public void saveFile(HtmlInputFile FU, string FD, string Project_ID)
    {
        string AttachDir = System.Configuration.ConfigurationSettings.AppSettings["AttachDir"];
        string AttachVirtualDir = System.Configuration.ConfigurationSettings.AppSettings["AttachVirtualDir"];
        string path = "";
        string url = "";
        string fn = System.IO.Path.GetFileName(FU.PostedFile.FileName);
        DirectoryInfo di;
        string strSql = "";

        //if (Project_ID != "")
        //{
        di = new DirectoryInfo(AttachDir + "\\project" + "\\" + Project_ID + "\\");
        path = AttachDir + "\\project" + "\\" + Project_ID + "\\";
        url = "http://" + HttpContext.Current.Server.MachineName + "/" + AttachVirtualDir + "/project" + "/" + Project_ID + "/" + fn;
        strSql = @" insert into tms_attachment (project_id, file_desc, file_link)
                    values ('{0}',?,?)";
        strSql = string.Format(strSql, Project_ID, url);
        //}

        if (!di.Exists)
            di.Create();

        FU.PostedFile.SaveAs(path + fn);

        OleDbConnection myConnection = new OleDbConnection(System.Configuration.ConfigurationSettings.AppSettings["dsn"]);
        myConnection.Open();
        OleDbCommand myCommand = new OleDbCommand(strSql, myConnection);
        myCommand.Parameters.Add(new OleDbParameter("@file_desc", OleDbType.VarChar, 200));
        myCommand.Parameters["@file_desc"].Value = FD;

        myCommand.Parameters.Add(new OleDbParameter("@file_link", OleDbType.VarChar, 500));
        myCommand.Parameters["@file_link"].Value = url;

        myCommand.ExecuteNonQuery();
        myConnection.Close();
    }