Ejemplo n.º 1
0
 public string img(FileUpload upload)
 {
     string str = "";
     string filename = upload.FileName;
     if (filename.Equals(""))
     {
         MessShowBox.show("图片不能为空", this);
     }
     else
     {
         string type = filename.Substring(filename.LastIndexOf(".") + 1).ToLower();
         if (type == "jpg" || type == "bmp" || type == "gif" || type == "png")
         {
             str = "/public/user_img/" + DateTime.Now.ToString("yyyyMMddhhmmss") + filename;
             if (!File.Exists(filename))
             {
                 upload.SaveAs(MapPath(str));
             }
             else
             {
                 MessShowBox.show("文件已存在,请重命名后再上传", this);
             }
         }
         else
         {
             MessShowBox.show("上传的图片个是不正确,图片格式必须是|jpg|bmp|gif|png", this);
         }
     }
     return str;
 }
Ejemplo n.º 2
0
        public static Guid UploadAttach(FileUpload fu)
        {
            if (!fu.HasFile || fu.FileName.Length == 0)
            {
                throw new BusinessObjectLogicException("Please select upload file!");
            }

            string path = null;
            try
            {
                string subDirectory = DateTime.Now.ToString("yyyyMM") + Path.DirectorySeparatorChar + DateTime.Now.ToString("dd");
                string directory = System.Configuration.ConfigurationManager.AppSettings["File"] + subDirectory;

                if (!Directory.Exists(directory)) Directory.CreateDirectory(directory);

                string title = Path.GetFileNameWithoutExtension(fu.FileName);
                string ext = Path.GetExtension(fu.FileName);

                path = Path.DirectorySeparatorChar + Path.GetRandomFileName() + ext;

                fu.SaveAs(directory + path);

                Attachment attach = new Attachment(UserHelper.UserName);
                attach.Title = title;
                attach.Path = subDirectory + path;

                new AttachmentBl().AddAttach(attach);

                return attach.UID;
            }
            catch
            {
                throw new BusinessObjectLogicException("File upload fail!");
            }
        }
Ejemplo n.º 3
0
 public static string FullPath(FileUpload fileUpload, string FileName, int MaxLength, string AbsolutePath)
 {
     string textId = "";
     if (!string.IsNullOrEmpty(FileName))
         textId = UnicodeConversion.CreateInstant().GetStringId(FileName);
     return FullPath(fileUpload, AbsolutePath, textId, MaxLength);
 }
Ejemplo n.º 4
0
    public static bool DosyaKaydet(this System.Web.UI.WebControls.FileUpload fileupload, string yol, out string dosya, out string mesaj)
    {
        mesaj = "";
        dosya = yol;
        if (fileupload.HasFile)
        {
            string dosyamiz = fileupload.FileName.ToLower();
            try
            {
                string resimurl = ClassBLL.ZamanaGoreResimAdiGetir();

                dosya += "/" + resimurl;

                string yeniyol = System.Web.HttpContext.Current.Server.MapPath(yol) + "\\" + resimurl;

                fileupload.SaveAs(yeniyol);

                return(true);
            }
            catch (Exception exc)
            {
                mesaj = exc.Message;
            }
            return(false);
        }
        return(false);
    }
Ejemplo n.º 5
0
    //<ذخيره فايل در مکان فيزيکي>
    public void Save_File(System.Web.UI.WebControls.FileUpload File_Upload, string Address)
    {
        string str = "";

        str = Server.MapPath(Address);
        File_Upload.PostedFile.SaveAs(str);
    }
Ejemplo n.º 6
0
 public string FileSc(FileUpload PosPhotoUpload, string saveFileName, string imagePath)
 {
     string state = "";
     if (PosPhotoUpload.HasFile)
     {
         if (PosPhotoUpload.PostedFile.ContentLength / 1024 < 10240)
         {
             string MimeType = PosPhotoUpload.PostedFile.ContentType;
             if (String.Equals(MimeType, "image/gif") || String.Equals(MimeType, "image/pjpeg"))
             {
                 PosPhotoUpload.PostedFile.SaveAs(HttpContext.Current.Server.MapPath(imagePath));
             }
             else
             {
                 state = "";
             }
         }
         else
         {
             state = "";
         }
     }
     else
     {
         state = "";
     }
     return state;
 }
Ejemplo n.º 7
0
 /// <summary>
 /// 文件上传
 /// </summary>
 /// <param name="path">保存路径</param>
 /// <param name="filleupload">上传文件控件</param>
 /// <param name="filename">文件名</param>
 /// <param name="fileExtension">后缀名</param>
 /// <param name="filesize">文件大小</param>
 /// <returns></returns>
 public static string FileUpload(FileUpload filleupload, string path, out string filename, out string fileExtension, out string filesize)
 {
     string FileName = CommonHelper.GetGuid;
     if (Directory.Exists(path) == false)//如果不存在就创建file文件夹
     {
         Directory.CreateDirectory(path);
     }
     //取得文件的扩展名,并转换成小写
     string Extension = System.IO.Path.GetExtension(filleupload.FileName).ToLower();
     fileExtension = Extension;
     filename = FileName + Extension;
     //取得文件大小
     filesize = FileHelper.CountSize(filleupload.PostedFile.ContentLength);
     try
     {
         int Size = filleupload.PostedFile.ContentLength / 1024 / 1024;
         if (Size > 10)
         {
             return "上传失败,文件过大";
         }
         else
         {
             filleupload.PostedFile.SaveAs(path + filename);
             return "上传成功";
         }
     }
     catch (Exception)
     {
         return "上传失败";
     }
 }
        public ActionResult Create(HttpPostedFileBase file)
        {
            //foreach (string file in Request.Files)
            //{
            //	HttpPostedFile hpf = Request.Files[file] as HttpPostedFile;
            //	if (hpf.ContentLength == 0)
            //		continue;
            //	string savedFileName = Path.Combine(
            //	   AppDomain.CurrentDomain.BaseDirectory,
            //	   Path.GetFileName(hpf.FileName));
            //	hpf.SaveAs(savedFileName);
            //}

            Flyer flyer = new Flyer();
            if (TryUpdateModel(flyer))
            {
                //UPLOAD THE FLYER
                FileUpload uploader = new FileUpload();
                var fileName = Path.GetFileName(file.FileName);
                var path = Path.Combine(Server.MapPath("~/resources/flyers"), fileName);
                file.SaveAs(path);
                flyer.Location = path;
                _flyerRepository.Create(flyer);
                //TODO create flyer
                //flyers.CreateFlyer(flyer);
                return RedirectToAction("Index");
            }

            return View();
        }
Ejemplo n.º 9
0
        private static HtmlTableCell AddControl(JobControl_Get_Result control)
        {
            HtmlTableCell cell = new HtmlTableCell();
            Control c = new Control();

            switch (control.ControlTypeName)
            {
                case "TextBox":
                    c = new TextBox();
                    c.ID = control.JobControlID + control.ControlTypeName + control.ControlName;
                    break;

                case "CheckBox":
                    c = new CheckBox();
                    c.ID = control.JobControlID + control.ControlTypeName + control.ControlName;
                    break;

                case "ImageUpload":
                    c = new FileUpload();
                    c.ID = control.JobControlID + control.ControlTypeName + control.ControlName;
                    break;
            }

            cell.Controls.Add(c);
            return cell;
        }
Ejemplo n.º 10
0
        private string UploadBrandLogo(int BrandID,FileUpload fu)
        {
            string ImageUrl, ImageShortUrl, Message;
            CommonImageUpload.Upload(fu, out ImageUrl, out ImageShortUrl, out Message);

            return ImageShortUrl;
        }
Ejemplo n.º 11
0
 /// <summary>
 /// 上传图片
 /// </summary>
 /// <param name="fuControl"></param>
 /// <returns></returns>
 private string UploadPhoto(System.Web.UI.WebControls.FileUpload fuControl)
 {
     #region   图片功能
     string photoName = "";
     try
     {
         //图片文件夹
         string rootDir = Server.MapPath("../../upload/labUploadFiles/");
         //上传图片,生成文件保存目录名
         string fileName = new FileInfo(fuControl.FileName).Name;
         //当前时间,精确到毫秒6位
         string randomName = DateTime.Now.ToString("yyyyMMddHHmmffffff");
         photoName = randomName + fileName.Substring(fileName.IndexOf("."));
         //文件存放到程序上的路径
         string fileDir = rootDir + "/" + photoName;
         fuControl.SaveAs(fileDir);
         return(photoName);
     }
     catch (Exception ex)
     {
         MessageBoxShow(ex.Message, MessageBoxIcon.Error);
         return(photoName);
     }
     #endregion
 }
Ejemplo n.º 12
0
 public string Upload(FileUpload fileUpload, string ftpServerIP, string ftpUserID, string ftpPassword)
 {
     string filename = fileUpload.FileName;
     string sRet = "上传成功!";
     FileInfo fileInf = new FileInfo(fileUpload.PostedFile.FileName);
     string uri = "ftp://" + ftpServerIP + "/" + filename;
     FtpWebRequest reqFTP = (FtpWebRequest)WebRequest.Create(new Uri(uri));
     reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
     reqFTP.KeepAlive = false;
     reqFTP.Method = "STOR";
     reqFTP.UseBinary = true;
     reqFTP.UsePassive = false;
     reqFTP.ContentLength = fileInf.Length;
     int buffLength = 2048;
     byte[] buff = new byte[buffLength];
     FileStream fs = fileInf.OpenRead();
     try
     {
         Stream strm = reqFTP.GetRequestStream();
         for (int contentLen = fs.Read(buff, 0, buffLength); contentLen != 0; contentLen = fs.Read(buff, 0, buffLength))
         {
             strm.Write(buff, 0, contentLen);
         }
         strm.Close();
         fs.Close();
     }
     catch (Exception ex)
     {
         sRet = ex.Message;
     }
     return sRet;
 }
Ejemplo n.º 13
0
 /// <summary>
 /// 上传文件
 /// </summary>
 /// <param name="PosPhotoUpload">控件</param>
 /// <param name="saveFileName">保存的文件名</param>
 /// <param name="imagePath">保存的文件路径</param>
 public string FileSc(FileUpload PosPhotoUpload, string saveFileName, string imagePath)
 {
     string state = "";
     if (PosPhotoUpload.HasFile)
     {
         if (PosPhotoUpload.PostedFile.ContentLength / 1024 < 10240)
         {
             string MimeType = PosPhotoUpload.PostedFile.ContentType;
             if (String.Equals(MimeType, "image/gif") || String.Equals(MimeType, "image/pjpeg"))
             {
                 string extFileString = System.IO.Path.GetExtension(PosPhotoUpload.PostedFile.FileName);
                 PosPhotoUpload.PostedFile.SaveAs(HttpContext.Current.Server.MapPath(imagePath));
             }
             else
             {
                 state = "上传文件类型不正确";
             }
         }
         else
         {
             state = "上传文件不能大于10M";
         }
     }
     else
     {
         state = "没有上传文件";
     }
     return state;
 }
Ejemplo n.º 14
0
        private static FileUpload GetFileUpload(string id)
        {
            FileUpload fileUpload = new FileUpload();
            fileUpload.ID = id;

            return fileUpload;
        }
Ejemplo n.º 15
0
    protected bool check(System.Web.UI.WebControls.FileUpload postedFile, int size, string filetype)
    {
        bool   a        = false;
        int    fileSize = postedFile.PostedFile.ContentLength / 1024;
        string strtype  = System.IO.Path.GetExtension(postedFile.PostedFile.FileName);//扩展名

        //是否限制文件类型
        if (filetype.Length > 0)
        {
            if (filetype.ToLower().Equals("default"))
            {
                if (strtype.ToLower() != ".jpg" && strtype.ToLower() != ".bmp" && strtype.ToLower() != ".gif")
                {
                    a = false;
                }
                else
                {
                    a = true;
                }
            }
        }
        //是否限制大小
        if (size > 0)
        {
            if (fileSize <= size)
            {
                a = true;
            }
        }
        return(a);
    }
Ejemplo n.º 16
0
        public string fileupload(string name, int id)
        {
            string fileth = "";
            string str = "";
            string fid = name;
            if (File(name))
            {
                if (PdMusic(fid))
                {
                    fid = name.Substring(0, name.LastIndexOf('.')) + "_IMG" + DateTime.Now.ToString("yyyyHHmmssfff") + Path.GetExtension(name);
                }
                fileth = "~/upload/images/" + fid;
                FileInfo filee = new FileInfo(Server.MapPath(fileth));//删除以前的老文件
                if (filee.Exists)
                {
                    filee.Delete();
                }
                FileUpload FiLe = new FileUpload();
                FiLe.SaveAs(Server.MapPath(fileth));
                //判断是修改状态,还是添加状态
                if (id == 0)//添加
                {
                }
                else
                {//修改
                    Daxu.Entity.newlist newlistInfo = new Daxu.Entity.newlist();
                    newlistInfo.cnen = fid;
                    Daxu.BLL.newlistBll.UpdateInewlist(newlistInfo);
                }
                str = fid;

            }
            return str;
            // return "你好!";
        }
Ejemplo n.º 17
0
        /// <summary>
        /// 单文件上传
        /// </summary>
        /// <param name="file">文件上传控件</param>
        /// <param name="filetype">文件类型限制 例:new string[]{"image/gif","image/pjpeg"}</param>
        /// <param name="fileLength">文件大小限制[KB]</param>
        /// <param name="fullPath">文件要上传到的文件夹[全路径,不要带末尾的"\"] 例:Server.MapPath("../uploads")</param>
        /// <returns>上传后的文件名</returns>
        static public string Upload(System.Web.UI.WebControls.FileUpload file, string[] filetype, int fileLength, string fullPath)
        {
            bool checkType = false;

            foreach (string str in filetype)
            {
                if (file.PostedFile.ContentType.ToString() == str)
                {
                    checkType = true;
                    break;
                }
            }
            if (!checkType)
            {
                return("错误:您上传的文件是不允许的类型");
            }
            else
            {
                if (file.PostedFile.ContentLength > fileLength * 1024)
                {
                    return("错误:文件超出大小限制!");
                }
                else
                {
                    Random rand     = new Random(unchecked ((int)DateTime.Now.Ticks));
                    string extender = Path.GetExtension(file.PostedFile.FileName);
                    string filename = DateTime.Now.ToShortDateString().Replace("-", "") + rand.Next().ToString().Substring(0, 5) + extender;
                    file.PostedFile.SaveAs(fullPath + "\\" + filename);
                    return(filename);
                }
            }
        }
Ejemplo n.º 18
0
        protected void btnpdfUpload_Click(object sender, EventArgs e)
        {
            try
            {
                FileUpload FilePP = new FileUpload();
                FilePP = pdfFileUpload;
                if (FilePP.HasFile)
                {

                    string getExtention = Path.GetExtension(FilePP.FileName);

                    //path = path + @"\" + PPImg;

                    //FilePP.PostedFile.SaveAs(path);

                    if (getExtention == ".pdf" || getExtention == ".PDF")
                    {

                        // hidFileName.Value = filename;
                        // string path = HttpContext.Current.Server.MapPath(WebConfigurationManager.AppSettings["AttachmentPath"] + "/ModuleContents/");
                        string loc = "/download/";
                        string path = HttpContext.Current.Server.MapPath(loc);
                        if (!Directory.Exists(path))
                        {
                            Directory.CreateDirectory(path);
                        }

                        path = path + "fxpresent" + getExtention;

                        FilePP.PostedFile.SaveAs(path);
                        string message = "Message is <span class='actionTopic'>Your File Uploaded successfully.</span> Successfully.";
                        MyAlertBox("var callbackOk = function () { window.location = \"\"; }; SuccessAlert(\"" +
                                   "Process Succeed" + "\", \"" + message + "\", \"\");");

                    }
                    else
                    {
                        string message = "Message is <span class='actionTopic'>Your File extension does not match.</span> Successfully.";
                        MyAlertBox("var callbackOk = function () { window.location = \"\"; }; WarningAlert(\"" +
                                   "Process Succeed" + "\", \"" + message + "\", \"\");");

                    }

                }
                else
                {
                    string message = " <span class='actionTopic'>" + "Sorry Please Select Your File." + "</span>.";
                    MyAlertBox("var callbackOk = function () { window.location = \"\"; }; WarningAlert(\"" + "Warning!!" + "\", \"" + message + "\",\"\");");

                }

            }
            catch (Exception ex)
            {
                string message = ex.Message;
                if (ex.InnerException != null) { message += " --> " + ex.InnerException.Message; }
                MyAlertBox("ErrorAlert(\"" + ex.GetType() + "\", \"" + message + "\", \"\");");

            }
        }
Ejemplo n.º 19
0
 public static bool CheckContainImage(FileUpload ful)
 {
     //TODO: Kiem tra anh xem ng dùng có chọn ko?
     if (ful.HasFile)
         return true;
     else return false;
 }
Ejemplo n.º 20
0
        public UploadBinary()
        {
            InnerControlID = "FileUploader";
            _fileUploadControl = new FileUpload { ID = InnerControlID };
            _info = new Label { ID = "FileUploaderInfo" };

        }
Ejemplo n.º 21
0
        public static string UploadFile(FileUpload fileUpload)
        {
            if (fileUpload == null)
            {
                return string.Empty;
            }

            var tempMediaPath = ConfigurationHelper.GetScrudParameter("TempMediaPath");
            var uploadDirectory = HttpContext.Current.Server.MapPath(tempMediaPath);

            if (!Directory.Exists(uploadDirectory))
            {
                Directory.CreateDirectory(uploadDirectory);
            }

            var id = Guid.NewGuid().ToString();

            if (fileUpload.HasFile)
            {
                id += Path.GetExtension(fileUpload.FileName);
                id = Path.Combine(uploadDirectory, id);

                fileUpload.SaveAs(id);
            }

            return id;
        }
Ejemplo n.º 22
0
    private void FileUpload(System.Web.UI.WebControls.FileUpload iFile)
    {
        string virtualPath  = "../images/stg/";
        string absolutePath = Server.MapPath(virtualPath);
        string fullFilePath = "";

        if (!Directory.Exists(absolutePath))
        {
            DirectoryInfo objFold = Directory.CreateDirectory(absolutePath);
            absolutePath = objFold.FullName;
        }

        if (this.IType == "D")
        {
            fullFilePath = absolutePath + hdfImagePath.Value;
            if (File.Exists(fullFilePath))
            {
                File.Delete(fullFilePath);
            }
        }
        else
        {
            fullFilePath = absolutePath + iFile.FileName;
            if (File.Exists(fullFilePath))
            {
                File.SetAttributes(fullFilePath, FileAttributes.Normal);
                File.Delete(fullFilePath);
            }
            iFile.SaveAs(fullFilePath);
        }
    }
Ejemplo n.º 23
0
        public static byte[] getImage(System.Web.UI.WebControls.FileUpload fileUploadPhoto)
        {
            Stream       fileStream   = fileUploadPhoto.PostedFile.InputStream;
            BinaryReader binaryReader = new BinaryReader(fileStream);

            return(binaryReader.ReadBytes((int)fileStream.Length));
        }
 public  enum enumState{ noFile,fileEx,fileSuccess,fileFailed};//0没选中文件;1扩展名出错;2成功;3失败;
 //图片上传
 public enumState AlbumImageUpLoad(FileUpload fileUpload, string urlPath, string filename)
 {
     if (fileUpload.PostedFile.FileName == "")
     { 
         return enumState.noFile;
     }
     else
     {
         string filepath = fileUpload.PostedFile.FileName; 
         string fileEx = filepath.Substring(filepath.LastIndexOf(".") + 1);//string filename = lbRandomCode.Text + "."; 
         string serverpath = urlPath + filename + "." + fileEx;                //string serverpath = Server.MapPath("~/Images/Album/") + filename + fileEx;
         if (fileEx == "jpg" || fileEx == "bmp" || fileEx == "gif" || fileEx == "JPG" || fileEx == "BMP" || fileEx == "GIF")
         {
             fileUpload.PostedFile.SaveAs(serverpath);
             //imgAlbumCover.ImageUrl = "~/Images/Album/" + filename + fileEx;
             //lbImageUrl.Text = "~/Images/Album/" + filename + fileEx; 
             //imgAlbumCover.ImageUrl = lbImageUrl.Text;
             return enumState.fileSuccess;
         }
         else
         {
             return enumState.fileEx;
         }
     } 
 }
Ejemplo n.º 25
0
    public void FileUpload(string BJNo, System.Web.UI.WebControls.FileUpload FileUpLoader, out string lj, out string filname)//System.Web.UI.HtmlControls.HtmlInputFile
    {
        string filename = "";
        string yjpath   = "";

        if (FileUpLoader.PostedFile.FileName.Length != 0)
        {
            filename = FileUpLoader.PostedFile.FileName;
            if (filename.Contains("\\") == true)
            {
                filename = filename.Substring(filename.LastIndexOf("\\") + 1);
            }

            string MapDir = MapPath("~");
            yjpath = MapDir + savepath + "\\" + BJNo;
            if (!System.IO.Directory.Exists(yjpath))
            {
                System.IO.Directory.CreateDirectory(yjpath);//不存在就创建目录
            }
            FileUpLoader.PostedFile.SaveAs(yjpath + "\\" + filename);

            // FileSaveToDB(BJNo,  filename);
        }

        lj      = filename == "" ? "" : (yjpath + "\\" + filename);
        filname = filename;
        // Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "layer.msg('文件保存成功!')", true);
    }
Ejemplo n.º 26
0
    /*===本函數需傳入6個參數
     * '===1.System.Web.UI.WebControls.FileUpload檔案上傳物件
     * '===2.儲存路徑
     * '===3.檔名
     * '===4.整個Page
     * '===5.照片的寬度
     * '===6.照片的高度
     */
    public string[] FunUpLoadPic(System.Web.UI.WebControls.FileUpload Up, string SaveStr, string FName, int SWidth, int SHeight)
    {
        string[] tmparr = new string[20];
        //' MsgBox(Up.PostedFile.FileName)

        if (Up.PostedFile.FileName != null)
        {
            System.IO.Stream Fs = Up.PostedFile.InputStream; //'===宣告資料流
            int PicValue;                                    // '===宣告縮放比例
            Up.PostedFile.SaveAs(SaveStr + "/B" + FName);    // '===儲存原始圖
            if (SWidth > 0)
            {
                System.Drawing.Bitmap PicChk, PicB, PicS;   //'===宣告點陣圖
                PicChk = new System.Drawing.Bitmap(Fs);
                //' If PicChk.Width > PicChk.Height Then '===只接受寬度>高度的圖片
                PicValue = SWidth / PicChk.Width;
                //'PicB = New System.Drawing.Bitmap(Drawing.Image.FromStream(Fs), PicChk.Width * PicValue, PicChk.Height * PicValue)
                // 'PicB.Save(SaveStr & "B" & FName)
                var s = System.Drawing.Image.FromStream(Fs);
                PicS = new System.Drawing.Bitmap(s, PicChk.Width * (int)PicValue, PicChk.Height * (int)PicValue);
                PicS.Save(SaveStr + "/S" + FName);
            }
            tmparr[0] = "B" + FName;
            tmparr[1] = "S" + FName;
            //'End If
        }
        return(tmparr);
    }
Ejemplo n.º 27
0
        public static string GetSavedFile(FileUpload fUploader, bool autoGenerateName)
        {
            string guid = string.Empty;

            if (fUploader.PostedFile != null)
            {
                try
                {
                    if (!fUploader.PostedFile.FileName.Contains('.'))
                        return guid;
                    string[] fileext = fUploader.PostedFile.FileName.Split('.');
                    if (autoGenerateName)
                    {
                        guid = Guid.NewGuid().ToString();
                        guid += "." + fileext[fileext.Length - 1].ToString();
                    }
                    else
                        guid = fUploader.PostedFile.FileName;

                    SaveJPGWithCompressionSetting(fUploader.FileContent, ExpressoConfig.GeneralConfigElement.GetPhysicalUploadPath + guid);
                }
                catch (Exception ex)
                {
                    throw ex;
                }

            }
            return guid;
        }
Ejemplo n.º 28
0
    public void UpLoad(string path, System.Web.UI.WebControls.FileUpload fileupload)
    {
        bool fileOK = false;

        if (fileupload.HasFile)
        {
            string   fileException    = System.IO.Path.GetExtension(fileupload.FileName).ToLower();
            string[] allowedException = { ".docx", ".xlsx", ".xls", ".doc", ".mpp", ".rar", ".zip", ".vsd", ".txt", ".jpg", ".gif", ".bmp", ".png", ".swf", ".avi", ".mp3", ".rm", ".wma", ".wmv" };
            for (int i = 0; i < allowedException.Length; i++)
            {
                if (fileException == allowedException[i])
                {
                    fileOK = true;
                }
            }
        }
        if (fileOK)
        {
            //判断文件是否存在,不存在则创建路径
            if (System.IO.Directory.Exists(path))
            {
                //该目录存在,则将上传的文件保存在该目录当中;
            }
            else
            {
                System.IO.Directory.CreateDirectory(path);
            }

            fileupload.SaveAs(path + "\\" + fileupload.FileName);
        }
        else
        {
            throw new Exception("不支持此格式文件上传!");
        }
    }
        protected String fileUploadName(FileUpload fileupload)
        {
            try
            {
                string fileUploadDir = Server.MapPath(General.EMP_ARTICLE_LOGO + txt_Title.Text.Trim() + "/");
                if (!System.IO.Directory.Exists(fileUploadDir))
                {
                    System.IO.Directory.CreateDirectory(fileUploadDir);
                }

                System.Drawing.Image imageToBeResized = System.Drawing.Image.FromStream(fileupload.PostedFile.InputStream);
                int imageHeight = imageToBeResized.Height;
                int imageWidth = imageToBeResized.Width;
                int maxHeight = 196;
                int maxWidth = 300;
                imageHeight = (imageHeight * maxWidth) / imageWidth;
                imageWidth = maxWidth;
                if (imageHeight > maxHeight)
                {
                    imageWidth = (imageWidth * maxHeight) / imageHeight;
                    imageHeight = maxHeight;
                }
                Bitmap bitmap = new Bitmap(imageToBeResized, imageWidth, imageHeight);
                bitmap.Save(fileUploadDir + fileupload.FileName);

                return fileupload.PostedFile.FileName.ToString();
            }
            catch (Exception)
            {
                return "";
            }
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Processes all upload controls in a control collection when the module is not installed.
        /// </summary>
        /// <param name="cc">Control collection.</param>
        /// <param name="defaultProcessor">The default processor.</param>
        /// <param name="status">The upload status.</param>
        void ProcessUploadControls(ControlCollection cc, IFileProcessor defaultProcessor, UploadStatus status)
        {
            foreach (Control c in cc)
            {
                System.Web.UI.WebControls.FileUpload fu = c as System.Web.UI.WebControls.FileUpload;

                if (fu != null && fu.HasFile)
                {
                    IFileProcessor controlProcessor = GetProcessorForControl(fu);
                    IFileProcessor processor        = controlProcessor == null ? defaultProcessor : controlProcessor;

                    try
                    {
                        processor.StartNewFile(fu.FileName, fu.PostedFile.ContentType, null, null);
                        processor.Write(fu.FileBytes, 0, fu.FileBytes.Length);
                        processor.EndFile();

                        status.UploadedFiles.Add(new UploadedFile(fu.FileName, processor.GetIdentifier(), null));
                    }
                    catch (Exception ex)
                    {
                        status.ErrorFiles.Add(new UploadedFile(fu.FileName, processor.GetIdentifier(), null, ex));
                    }
                }

                if (c.HasControls())
                {
                    ProcessUploadControls(c.Controls, defaultProcessor, status);
                }
            }
        }
        private Byte[] resizeImage(FileUpload fileUpload, int width, int height)
        {
            //
            //Get file extension
            //
            string fileExtension = Path.GetExtension(fileUpload.PostedFile.FileName);

            //
            //Generate thumbnail image
            //
            MemoryStream mstrOut = new MemoryStream();
            System.Drawing.Image img = System.Drawing.Image.FromStream(new MemoryStream(fileUpload.FileBytes));
            img = img.GetThumbnailImage(183, 51, null, IntPtr.Zero);

            //
            //Verify file extension
            //
            if (fileExtension.ToUpper() == ".GIF")
                img.Save(mstrOut, System.Drawing.Imaging.ImageFormat.Gif);

            if (fileExtension.ToUpper() == ".JPG")
                img.Save(mstrOut, System.Drawing.Imaging.ImageFormat.Jpeg);

            if (fileExtension.ToUpper() == ".PNG")
                img.Save(mstrOut, System.Drawing.Imaging.ImageFormat.Png);

            return mstrOut.ToArray();
        }
Ejemplo n.º 32
0
 public Imagem(FileUpload FileUpload, HiddenField Hidden, string Path, string Arquivo)
 {
     this.FileUpload = FileUpload;
     this.Hidden = Hidden;
     this.Path = Path;
     this.Arquivo = Arquivo;
 }
Ejemplo n.º 33
0
 /// <summary>
 /// 上传文件
 /// </summary>
 /// <param name="postedFile">上传文件控件</param>
 /// <param name="path">存入的物理路径,留空则为根目录下 UploadFile 目录</param>
 /// <param name="size">文件大小,0为不限制</param>
 /// <param name="filetype">可上传的文件类型,格式:".gif|.jpg|.png",留空为不限制,"default"即默认".gif|.jpg|.bmp"类型</param>
 /// <returns>上传后文件的名称 返回1:文件类型不对 返回2:大小超出限制</returns>
 public string UploadFile(System.Web.UI.WebControls.FileUpload postedFile, string path, int size, string filetype, bool isNo)
 {
     try
     {
         string   strSaveName = string.Empty;
         string   strtype     = System.IO.Path.GetExtension(postedFile.PostedFile.FileName); //扩展名
         DateTime Now         = DateTime.Now;
         if (isNo)                                                                           //默认图片
         {
             strSaveName = "/dservice/image/" + Now.Year.ToString() + "/" + Now.Year.ToString() + Now.Month.ToString() + Now.Day.ToString() +
                           Now.Hour.ToString() + Now.Minute.ToString() + Now.Second.ToString() + strtype;
         }
         else
         {
             strSaveName = ViewState["strSavePath"].ToString();
         }
         if (!Directory.Exists(path))
         {
             Directory.CreateDirectory(path);
         }
         string[] strImage    = strSaveName.Split(new char[] { '/' });
         string   strSavePath = path + strImage[strImage.Length - 1];//为文件获取保存路径
         ViewState["strSavePath"] = strSaveName;
         int fileSize = postedFile.PostedFile.ContentLength / 1024;
         //是否限制文件类型
         if (filetype.Length > 0)
         {
             if (filetype.ToLower().Equals("default"))
             {
                 if (strtype.ToLower() != ".jpg" && strtype.ToLower() != ".bmp" && strtype.ToLower() != ".gif")
                 {
                     return("1");
                 }
             }
         }
         //是否限制大小
         if (size > 0)
         {
             if (fileSize <= size)
             {
                 postedFile.PostedFile.SaveAs(strSavePath);//保存上传的文件到指定的路径
                 return(strSaveName);
             }
             else
             {
                 //上传的文件大小超出
                 return("2");
             }
         }
         else
         {
             postedFile.PostedFile.SaveAs(strSavePath);//保存上传的文件到指定的路径
             return(strSaveName);
         }
     }
     catch (Exception ex)
     {
         throw;
     }
 }
Ejemplo n.º 34
0
    /// <summary>
    /// 文件上传(asp:FileUpload的对象myControl,服务器地址severUrl)
    /// </summary>
    /// <param name="myControl"></param>
    /// <param name="severUrl"></param>
    /// <returns></returns>
    public static bool SaveImg(System.Web.UI.WebControls.FileUpload myControl, string severUrl, string picName)
    {
        //获取文件的后缀名picLastName
        string localUrl    = myControl.PostedFile.FileName;//获取上传的文件路径(本地路径)
        int    index       = localUrl.LastIndexOf(".");
        string picLastName = localUrl.Substring(index);

        if (picLastName != ".jpeg" && picLastName != ".jpg" && picLastName != ".gif" && picLastName != ".png" && picLastName != ".bmp")
        {
            return(false);
        }
        //上传后的文件名
        string pictureName = null;

        pictureName = picName + picLastName;

        try
        {
            myControl.SaveAs(severUrl + "/" + pictureName);
            return(true);
        }
        catch (Exception ex)
        {
            return(false);
        }
    }
Ejemplo n.º 35
0
        public static string UploadFile(FileUpload fileUpload)
        {
            if (fileUpload == null)
            {
                return string.Empty;
            }

            //Todo: Parameterize media path.
            string uploadDirectory = HttpContext.Current.Server.MapPath("~/Media/Temp");
            if (!System.IO.Directory.Exists(uploadDirectory))
            {
                System.IO.Directory.CreateDirectory(uploadDirectory);
            }

            string id = Guid.NewGuid().ToString();

            if (fileUpload.HasFile)
            {
                id += System.IO.Path.GetExtension(fileUpload.FileName);
                id = System.IO.Path.Combine(uploadDirectory, id);

                fileUpload.SaveAs(id);
            }

            return id;
        }
Ejemplo n.º 36
0
 protected void LogoSourceSelectionList_SelectedIndexChanged(object sender, EventArgs e)
 {
     if (LogoSourceSelectionList.SelectedValue == "Computer")
     {
         Label LogoLabel = new Label();
         Label BreakLine = new Label();
         FileUpload LogotypeFileUpload = new FileUpload();
         BreakLine.Text = "<br />";
         LogoLabel.Text = "Please select an image from your computer:";
         LogotypePlaceHolder.Controls.Add(LogoLabel);
         LogotypePlaceHolder.Controls.Add(BreakLine);
         LogotypePlaceHolder.Controls.Add(LogotypeFileUpload);
     }
     if (LogoSourceSelectionList.SelectedValue == "Internet")
     {
         Label LogoLabel = new Label();
         Label BreakLine = new Label();
         TextBox LogoUrlTextBox = new TextBox();
         BreakLine.Text = "<br />";
         LogoLabel.Text = "Please specify the URL to the location of your logotype. Please make sure to specify an absolute path such as: http://www.something.com/image.png";
         LogoUrlTextBox.Text = "http://";
         LogotypePlaceHolder.Controls.Add(LogoLabel);
         LogotypePlaceHolder.Controls.Add(BreakLine);
         LogotypePlaceHolder.Controls.Add(LogoUrlTextBox);
     }
 }
Ejemplo n.º 37
0
        public string ProcessOtherFile(System.Web.UI.WebControls.FileUpload file, System.Web.UI.WebControls.CheckBox eliminarImagen, string ruta)
        {
            string retorno = "";

            if (!string.IsNullOrEmpty(file.PostedFile.FileName))
            {
                Random myRandom = new Random();
                string xName    = myRandom.Next(1, 1000000).ToString();
                if (IMFile.IMFile.GetNameFile(file.PostedFile.FileName).Length > 16)
                {
                    retorno = xName + "_" + IMFile.IMFile.GetNameFile(file.PostedFile.FileName).Substring(0, 16) + IMFile.IMFile.GetExtensionFile(file.PostedFile.FileName);
                }
                else
                {
                    retorno = xName + "_" + IMFile.IMFile.GetNameFile(file.PostedFile.FileName).Substring(0, IMFile.IMFile.GetNameFile(file.PostedFile.FileName).Length) + IMFile.IMFile.GetExtensionFile(file.PostedFile.FileName);
                }
                file.PostedFile.SaveAs(Server.MapPath(ruta + retorno));
            }
            if (eliminarImagen != null)
            {
                if (eliminarImagen.Checked)
                {
                    IMFile.IMFile.Delete(Server.MapPath(ruta + retorno));
                    retorno = "";
                    eliminarImagen.Checked = false;
                    eliminarImagen.Visible = false;
                }
            }
            return(retorno);
        }
Ejemplo n.º 38
0
        protected override void CreateChildControls()
        {
            FallbackPanel          = new Panel();
            FallbackPanel.ID       = "FallbackPanel";
            FallbackPanel.CssClass = "fallback";
            this.Controls.Add(FallbackPanel);

            FileFromMyComputer = new System.Web.UI.WebControls.FileUpload();
            if (!string.IsNullOrWhiteSpace(this.Accept))
            {
                FileFromMyComputer.Attributes["accept"] = this.Accept;
            }
            FileFromMyComputer.ID = "FileFromMyComputer";
            FallbackPanel.Controls.Add(FileFromMyComputer);

            Validator                 = new CustomValidator();
            Validator.ID              = "Validator";
            Validator.Display         = ValidatorDisplay.Dynamic;
            Validator.CssClass        = "dz-error-message";
            Validator.ForeColor       = Color.Empty;
            Validator.ServerValidate += new ServerValidateEventHandler(Validator_ServerValidate);
            FallbackPanel.Controls.Add(Validator);

            AcceptChangesButton    = new Button();
            AcceptChangesButton.ID = "AcceptChangesButton";
            AcceptChangesButton.CausesValidation  = false;
            AcceptChangesButton.UseSubmitBehavior = false;
            AcceptChangesButton.Style[HtmlTextWriterStyle.Display] = "none";
            AcceptChangesButton.Click += AcceptChangesButton_Click;
            this.Controls.Add(AcceptChangesButton);

            FilesStateField    = new HiddenField();
            FilesStateField.ID = "FilesStateField";
            this.Controls.Add(FilesStateField);
        }
Ejemplo n.º 39
0
        protected String fileUploadName(FileUpload fileupload, Label label, string userid)
        {
            try
            {
                if (fileupload.HasFile)
                {
                    //if (fileupload.PostedFile.ContentType == "image/jpeg")
                    if (IsValidImage(fileupload.PostedFile.FileName))
                    {
                        if (fileupload.PostedFile.ContentLength < 1024000)
                        {
                            string fileUploadDir = Server.MapPath(General.EMP_LOGO + userid + "/");
                            if (!System.IO.Directory.Exists(fileUploadDir))
                            {
                                System.IO.Directory.CreateDirectory(fileUploadDir);
                            }
                            System.Drawing.Image imageToBeResized = System.Drawing.Image.FromStream(fileupload.PostedFile.InputStream);
                            int imageHeight = imageToBeResized.Height;
                            int imageWidth = imageToBeResized.Width;
                            int maxHeight = 80;
                            int maxWidth = 106;
                            imageHeight = (imageHeight * maxWidth) / imageWidth;
                            imageWidth = maxWidth;
                            if (imageHeight > maxHeight)
                            {
                                imageWidth = (imageWidth * maxHeight) / imageHeight;
                                imageHeight = maxHeight;
                            }
                            Bitmap bitmap = new Bitmap(imageToBeResized, imageWidth, imageHeight);
                            bitmap.Save(Server.MapPath(General.EMP_LOGO + userid + "/") +
                                 fileupload.FileName);

                            label.Text = "File is selected!";
                            return fileupload.FileName;
                        }
                        else
                        {
                            label.Text = "Error: File upload has to be less than 1mb!";
                            return null;
                        }
                    }
                    else
                    {
                        label.Text = "Error: Only image can be uploaded!";
                        return null;
                    }
                }
                else
                {
                    label.Text = "Error: You have not specified a file!";
                    return null;
                }
            }
            catch (Exception ex)
            {
                label.Text = "Error: " + ex.Message.ToString();
                return null;
            }
        }
        //Try uploading the image for decryption
        public static IMAGE_UPLOAD_RESULT UploadImage(System.Web.UI.WebControls.FileUpload fileUpload, ref string _name)
        {
            IMAGE_UPLOAD_RESULT result = IMAGE_UPLOAD_RESULT.SUCCESS;
            //Get the file name
            string filename = Path.GetFileName(fileUpload.FileName);

            //Generate a new random name (GUID) for the image
            filename = Guid.NewGuid().ToString() + "_" + filename;

            //Save the file in the proper path with the proper name
            fileUpload.SaveAs(FolderPath + filename);

            //Check is it's not an image
            if (!isImage(FolderPath + filename))
            {
                result = IMAGE_UPLOAD_RESULT.FAILED;
            }
            else
            {
                //If it's an image
                try
                {
                    //Read the image data to check if it's valid
                    using (System.Drawing.Image myImage = System.Drawing.Image.FromStream(fileUpload.PostedFile.InputStream))
                    {
                        /* //If it's not a square
                         * if (myImage.Height != myImage.Width)
                         * {
                         *   //Display error because image isn't square
                         *   result = IMAGE_UPLOAD_RESULT.DIMNOTEQUAL;
                         * }*/
                        //Check if the image width is greater than the maximum width allowed (for memroy reasons)
                        if (myImage.Width > MAXWIDTH)
                        {
                            //Display error because image is too big
                            result = IMAGE_UPLOAD_RESULT.BIGFILE;
                        }
                    }
                }
                catch (Exception exp)
                {
                    //Display error because uploading has failed
                    result = IMAGE_UPLOAD_RESULT.FAILED;
                }
            }
            //If uploading was a success, set _name to the filename
            if (result == IMAGE_UPLOAD_RESULT.SUCCESS)
            {
                _name = filename;
            }
            else
            {
                //If it wasn't successful, delete the uploaded file
                DeleteFile(FolderPath + filename);
            }

            //Return the upload result
            return(result);
        }
Ejemplo n.º 41
0
 public static string GetExt(FileUpload FileUpload)
 {
     if (!((FileUpload != null) && FileUpload.HasFile))
     {
         throw new Exception("未選擇上傳檔案");
     }
     return Path.GetExtension(FileUpload.FileName).ToLower();
 }
Ejemplo n.º 42
0
        public IEnumerable<object> Render(PanelItem panelItem)
        {
            var upload = new FileUpload { Enabled = true, CssClass = ItemStyle};

            panelItem.Target = upload;

            return new List<Control> { upload }.Cast<object>();
        }
Ejemplo n.º 43
0
 public void SaveFile(string destination, System.Web.UI.WebControls.FileUpload file)
 {
     if (file.HasFile)
     {
         file.SaveAs(destination + file.FileName);
         file.Dispose();
     }
 }
 public string ImageToBase64(FileUpload img)
 {
     string base64String = "";
     MemoryStream m = new MemoryStream(img.FileBytes);
     byte[] imageBytes = m.ToArray();
     base64String = Convert.ToBase64String(imageBytes);
     return base64String;
 }
Ejemplo n.º 45
0
    public static string SetFileNamelast(System.Web.UI.WebControls.FileUpload myFile)
    {
        string temp = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString();

        temp += DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + "1";
        temp += System.IO.Path.GetExtension(myFile.PostedFile.FileName);
        return(temp);
    }
Ejemplo n.º 46
0
        protected String fileUploadName_candidate(FileUpload fileupload, Label label, string username)
        {
            try
            {
                if (fileupload.HasFile)
                {
                    //if (fileupload.PostedFile.ContentType == "image/jpeg")
                    if (IsValidImage(fileupload.PostedFile.FileName))
                    {
                        if (fileupload.PostedFile.ContentLength < General.IMAGE_SIZE)
                        {
                            string fileUploadDir = Server.MapPath(General.CAN_LOGO + username + "/");
                            if (!System.IO.Directory.Exists(fileUploadDir))
                            {
                                System.IO.Directory.CreateDirectory(fileUploadDir);
                            }
                            else
                            {
                                string[] filePaths = Directory.GetFiles(Server.MapPath(General.CAN_LOGO + username + "/"), "*.*",
                                             SearchOption.AllDirectories);

                                foreach (string path in filePaths)
                                {
                                    File.Delete(path);
                                }
                            }
                            //change image size
                            var image = System.Drawing.Image.FromStream(fileupload.PostedFile.InputStream);
                            var newImage = Utils.ScaleImage(image, 300, 300);
                            newImage.Save(Server.MapPath(General.CAN_LOGO + username + "/") + fileupload.FileName, ImageFormat.Jpeg);

                            label.Text = "Photo is selected!";
                            return fileupload.FileName;
                        }
                        else
                        {
                            label.Text = "Error: File upload has to be less than "+General.GetImageSize(General.IMAGE_SIZE)+"mb!";
                            return null;
                        }
                    }
                    else
                    {
                        label.Text = "Error: Only image can be uploaded!";
                        return null;
                    }
                }
                else
                {
                    label.Text = "Error: You have not specified a file!";
                    return null;
                }
            }
            catch (Exception ex)
            {
                label.Text = "Error: " + ex.Message.ToString();
                return null;
            }
        }
Ejemplo n.º 47
0
        /// <summary>
        /// 1:上傳檔案格式請參考:UI Spec Excel檔案格式。
        /// 2:檢查檔案Size大於0等必要檢查。
        /// 3:上傳檔案到AP_Server端暫存路徑,如有任何異常,則回傳錯誤訊息停止上傳流程。
        /// </summary>
        public ArrayList FileUpload(string s_UploadPath, FileUpload File_Upload, string s_LoginUser)
        {
            try
            {
                #region 宣告變數

                String s_fileExtension = string.Empty;//副檔名
                String s_fileWithoutExtension = string.Empty;//檔名不包含副檔名
                DateTime d_CreateDate = DateTime.Now;
                ArrayList arl_Return = new ArrayList();
                bool b_fileOK = false;

                #endregion

                # region 檢查上傳檔案的路徑與檔案格式

                s_fileExtension = System.IO.Path.GetExtension(File_Upload.FileName).ToLower();//副檔名
                s_fileWithoutExtension = System.IO.Path.GetFileNameWithoutExtension(File_Upload.FileName).ToLower();//檔名

                if (File_Upload.HasFile)
                {
                    String[] allowedExtensions ={ ".xls" };//在此設定允許上傳的檔案格式

                    for (int i = 0; i < allowedExtensions.Length; i++)
                    {
                        if (s_fileExtension == allowedExtensions[i])
                        { b_fileOK = true; }
                    }
                }

                #endregion

                #region 將檔案上傳至AP

                if (b_fileOK == true)
                {
                    //儲存的新檔名=原檔名_登入者_上傳時間.副檔名
                    s_UploadPath += s_fileWithoutExtension + "_" + s_LoginUser + "_" + d_CreateDate.ToString("yyyyMMddHHmmss") + s_fileExtension;
                    File_Upload.SaveAs(s_UploadPath);

                    arl_Return.Add("TRUE");
                    arl_Return.Add(s_UploadPath);
                    arl_Return.Add(d_CreateDate);
                    arl_Return.Add(s_fileWithoutExtension + "_" + s_LoginUser + "_" + d_CreateDate.ToString("yyyyMMddHHmmss") + s_fileExtension);
                }
                else
                {
                    arl_Return.Add("FALSE");
                    arl_Return.Add("路徑" + File_Upload.PostedFile.FileName + "不是正確的檔案");
                }

                #endregion

                return arl_Return;
            }
            catch (Exception ex)
            { throw ex; }
        }
Ejemplo n.º 48
0
        public static DataSet getDataSetFromExcel(FileUpload FileUpload1, HttpServerUtility Server)
        {
            if (FileUpload1.HasFile)
            {
                string fileName = Path.GetFileName(FileUpload1.FileName);
                string filePath = Server.MapPath("~/Excel/" + fileName);
                string fileExtension = System.IO.Path.GetExtension(FileUpload1.FileName);

                try
                {

                    MemoryStream stream = new MemoryStream(FileUpload1.FileBytes);
                    IExcelDataReader excelReader;

                    if (fileExtension == ".xls")
                    {
                        excelReader = ExcelReaderFactory.CreateBinaryReader(stream);

                        excelReader.IsFirstRowAsColumnNames = true;
                        DataSet result = excelReader.AsDataSet();

                        DataTable myTable = result.Tables[0];

                        excelReader.Close();
                        return result;
                    }
                    else if (fileExtension == ".xlsx")
                    {
                        excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);

                        //excelReader.IsFirstRowAsColumnNames = true;
                        DataSet result = excelReader.AsDataSet();

                        DataTable myTable = result.Tables[0];

                        excelReader.Close();
                        return result;
                    }
                    else if (fileExtension == ".csv")
                    {
                        //Someone else can implement this
                        return null;
                    }
                    else
                    {
                        throw new Exception("Unhandled Filetype");
                    }
                }
                catch
                {
                    return null;
                }
            }
            else
            {
                return null;
            }
        }
Ejemplo n.º 49
0
        protected void btnDeleteImage_Click(object sender, System.EventArgs e)
        {
            Button b = (Button)sender;

            System.Web.UI.WebControls.Image      img = (PnlBanners.FindControl(b.Attributes["ImageName"].ToString()) as System.Web.UI.WebControls.Image);
            System.Web.UI.WebControls.FileUpload fu  = (PnlBanners.FindControl(b.Attributes["FileUploadName"].ToString()) as System.Web.UI.WebControls.FileUpload);

            ImageFileHandler(fu, img, b);
        }
Ejemplo n.º 50
0
        protected void Button1_Click(object sender, EventArgs e)
        {
            this.m_FileExtArr = "doc|docx|txt";
            string str3       = "";
            string foldername = "";
            string filename   = "";
            string str2       = "";

            System.Web.UI.WebControls.FileUpload upload = (System.Web.UI.WebControls.FileUpload) this.FindControl("FileUpload1");
            StringBuilder builder2 = new StringBuilder();

            string uploadFile;

            if (SiteConfig.SiteOption.UploadDir == null)
            {
                uploadFile = "UploadFiles";
            }
            else
            {
                uploadFile = SiteConfig.SiteOption.UploadDir;
            }

            if (upload.HasFile)
            {
                str2 = Path.GetExtension(upload.FileName).ToLower();
                if (!this.CheckFilePostfix(str2.Replace(".", "")))
                {
                    builder2.Append("文档" + upload.FileName + "不符合图片扩展名规则" + this.m_FileExtArr + @"\r\n");
                }
                else
                {
                    if (((int)upload.FileContent.Length) > (100 * 0x400))
                    {
                        builder2.Append("文档" + upload.FileName + "大小超过100" + @"KB\r\n");
                    }
                    else
                    {
                        str3       = DataSecurity.MakeFileRndName();
                        foldername = base.Request.PhysicalApplicationPath + (VirtualPathUtility.AppendTrailingSlash("/" + uploadFile + "/Project")).Replace("/", "\\");// + this.FileSavePath()
                        filename   = FileSystemObject.CreateFileFolder(foldername, HttpContext.Current) + str3 + str2;
                        //SafeSC.SaveFile(filename,upload);
                        if (!FileUpload1.SaveAs(filename))
                        {
                            function.WriteErrMsg(FileUpload1.ErrorMsg);
                        }
                        builder2.Append("文档" + upload.FileName + @"上传成功\r\n");
                        this.TxtColumnDefault.Text = uploadFile + "/Project/" + str3 + str2;
                    }
                }
            }
            if (builder2.Length > 0)
            {
                string message = "<script language=\"javascript\" type=\"text/javascript\">alert('" + builder2.ToString() + "');</script>";
                function.Script(Page, "alert(message)");
            }
        }
Ejemplo n.º 51
0
    /// <summary>
    /// 上传文件
    /// </summary>
    /// <param name="postedFile">上传文件控件</param>
    /// <param name="path">存入的物理路径,留空则为根目录下 UploadFile 目录</param>
    /// <param name="size">文件大小,0为不限制</param>
    /// <param name="filetype">可上传的文件类型,格式:".gif|.jpg|.png",留空为不限制,"default"即默认".gif|.jpg|.bmp"类型</param>
    /// <returns>上传后文件的名称 返回1:文件类型不对 返回2:大小超出限制</returns>
    public string UploadFile(System.Web.UI.WebControls.FileUpload postedFile, string path, int size, string filetype)
    {
        try
        {
            // string strSaveName = string.Empty;
            //   string strtype = System.IO.Path.GetFileName(postedFile.PostedFile.FileName);//扩展名
            string strtype = System.IO.Path.GetExtension(postedFile.PostedFile.FileName);                                                                    //扩展名

            string strSaveName = System.DateTime.Now.ToLocalTime().ToString().Replace(":", "").Replace("-", "").Replace(" ", "").Replace("/", "") + strtype; //上传后的文件名称
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            string strSavePath = path + strSaveName;//为文件获取保存路径
            //  ViewState["strSavePath"] = strSaveName;
            int fileSize = postedFile.PostedFile.ContentLength / 1024;

            //是否限制文件类型
            if (filetype.Length > 0)
            {
                if (filetype.ToLower().Equals("default"))
                {
                    if (strtype.ToLower() != ".jpg" && strtype.ToLower() != ".bmp" && strtype.ToLower() != ".gif")
                    {
                        return("1");
                    }
                }
            }
            //是否限制大小
            if (size > 0)
            {
                if (fileSize <= size)
                {
                    postedFile.PostedFile.SaveAs(strSavePath);//保存上传的文件到指定的路径

                    return(strSaveName);
                }
                else
                {
                    //上传的文件大小超出
                    return("2");
                }
            }
            else
            {
                postedFile.PostedFile.SaveAs(strSavePath);//保存上传的文件到指定的路径

                return(strSaveName);
            }
        }
        catch (Exception ex)
        {
            throw;
        }
    }
Ejemplo n.º 52
0
 /// <summary>
 /// 上传图片
 /// </summary>
 /// <param name="postedFile">上传文件控件</param>
 /// <param name="path">存入的物理路径,留空则为根目录下 UploadFile 目录</param>
 /// <param name="size">文件大小,0为不限制</param>
 /// <param name="filetype">可上传的文件类型,格式:".gif|.jpg|.png",留空为不限制,"default"即默认".gif|.jpg|.bmp"类型</param>
 /// <returns>上传后文件的名称 返回1:文件类型不对 返回2:大小超出限制</returns>
 public string UploadFile(System.Web.UI.WebControls.FileUpload postedFile, string path, int size, string filetype)
 {
     try
     {
         loginName = ViewState["name"].ToString();
         string   strSaveName = string.Empty;
         string   strtype     = System.IO.Path.GetExtension(postedFile.PostedFile.FileName);//扩展名
         DateTime date        = DateTime.Now;
         strSaveName = date.Year.ToString() + date.Month.ToString() + date.Day.ToString() + date.Hour.ToString() + date.Minute.ToString() + date.Second.ToString() + date.Millisecond.ToString() + strtype;
         if (!Directory.Exists(path + loginName))
         {
             Directory.CreateDirectory(path + loginName);
         }
         string strSavePath = path + loginName + "/" + strSaveName;//为文件获取保存路径
         ViewState["strSavePath"] = strSaveName;
         int fileSize = postedFile.PostedFile.ContentLength / 1024;
         //是否限制文件类型
         if (filetype.Length > 0)
         {
             if (filetype.ToLower().Equals("default"))
             {
                 if (strtype.ToLower() != ".jpg" && strtype.ToLower() != ".bmp" && strtype.ToLower() != ".gif")
                 {
                     return("1");
                 }
             }
         }
         //是否限制大小
         if (size > 0)
         {
             if (fileSize <= size)
             {
                 postedFile.PostedFile.SaveAs(strSavePath);//保存上传的文件到指定的路径
                 //Response.Write(strSavePath);
                 return(strSaveName);
             }
             else
             {
                 //上传的文件大小超出
                 return("2");
             }
         }
         else
         {
             postedFile.PostedFile.SaveAs(strSavePath);//保存上传的文件到指定的路径
             //Response.Write(strSavePath);
             return(strSaveName);
         }
     }
     catch (Exception ex)
     {
         throw;
     }
 }
Ejemplo n.º 53
0
    public static string UploadFile(this System.Web.UI.WebControls.FileUpload file, string directorypath)
    {
        if (!file.HasFile)
        {
            return(null);
        }
        var fileName = Guid.NewGuid() + "_" + file.FileName;

        file.SaveAs(directorypath + fileName);
        return(fileName);
    }
Ejemplo n.º 54
0
    public static void Insert(string title, string author, string content, System.Web.UI.WebControls.FileUpload FU_Image)
    {
        Guid          guid             = Guid.NewGuid();
        string        url              = "";
        string        ConnectionString = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;
        SqlConnection conn             = new SqlConnection(ConnectionString);

        try
        {
            if (FU_Image.HasFiles)
            {
                HttpPostedFile last = FU_Image.PostedFiles.Last();
                foreach (HttpPostedFile uploadedFile in FU_Image.PostedFiles)
                {
                    string fileExtention = Path.GetExtension(uploadedFile.FileName.ToLower());
                    if (fileExtention == ".jpeg" || fileExtention == ".jpg" || fileExtention == ".png")
                    {
                        string FileName = Path.GetFileName(uploadedFile.FileName);

                        string rename = guid + FileName.Replace(" ", "_");

                        uploadedFile.SaveAs(System.Web.HttpContext.Current.Server.MapPath("~/pages/news/newsimages/" + rename));
                        if (uploadedFile.Equals(last))
                        {
                            url += "~/pages/news/newsimages/" + rename;
                        }
                        else
                        {
                            url += "~/pages/news/newsimages/" + rename + "\",\"";
                        }
                    }
                }
            }
            conn.Open();
            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.Connection  = conn;
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = SQLQuery.NewsInsert;
                cmd.Parameters.AddWithValue("@Title", title);
                cmd.Parameters.AddWithValue("@Author", author);
                cmd.Parameters.AddWithValue("@Content", content);
                cmd.Parameters.AddWithValue("@CreateDate", String.Format("{0:d/M/yyyy HH:mm:ss}", DateTime.Now));
                cmd.Parameters.AddWithValue("@Image", url);
                cmd.ExecuteNonQuery();
            }
            conn.Close();
        }
        catch (Exception e)
        {
            throw new Exception(e.Message);
        }
    }
Ejemplo n.º 55
0
    /// <summary>
    /// 上传图片(传递控件)
    /// </summary>
    /// <param name="myFile">控件名称</param>
    /// <param name="myFileName">文件名称</param>
    /// <param name="myFileSize">文件大小(M)</param>
    /// <param name="myFileType">允许上传的文件类别</param>
    /// <param name="mySaveDirectory">文件保存路径</param>
    /// <param name="file_fg">如果文件存在是否覆盖,TRUE覆盖,FALSE不覆盖</param>
    public static bool myUpFile(System.Web.UI.WebControls.FileUpload myFile, string myFileName, int myFileSize, string myFileType, string mySaveDirectory, string file_fg)
    {
        try
        {
            //判断文件是否存在或有数据
            if (myFile.PostedFile.ContentLength <= 0)
            {
                JsHelper.MsgBox("请选择您要上传的图片!");
                return(false);
            }

            //判断文件是否超过限制
            if (myFile.PostedFile.ContentLength / 1048576d > myFileSize)
            {
                JsHelper.MsgBox("上传的文件不能超过 " + myFileSize.ToString() + "M!");
                return(false);
            }

            //判断文件类别是否允许上传
            string myType = System.IO.Path.GetExtension(myFile.PostedFile.FileName).Substring(1).ToLower();
            if (myFileType.IndexOf(myType) < 0)
            {
                JsHelper.MsgBox("对不起,只允许 " + myFileType + " 类别的文件上传!");
                return(false);
            }

            //判断文件夹是否存在
            if (!Directory.Exists(mySaveDirectory))
            {
                Directory.CreateDirectory(mySaveDirectory);
            }

            //获取文件物理路径
            string mySaveFile = mySaveDirectory + myFileName;
            //判断文件是否存在
            if (System.IO.File.Exists(mySaveFile))
            {
                if (file_fg == "FALSE")
                {
                    JsHelper.MsgBox("文件已经存在,请选择其它要上传的文件!");
                    return(false);
                }
            }
            myFile.PostedFile.SaveAs(mySaveFile);
            return(true);
        }
        catch (Exception ex)
        {
            JsHelper.MsgBox(ex.Message);
            return(false);
        }
    }
Ejemplo n.º 56
0
 public static string UploadFile(this System.Web.UI.WebControls.FileUpload file, string directorypath, string filename)
 {
     if (!file.HasFile)
     {
         return(null);
     }
     if (filename.Trim().Length == 0)
     {
         return(file.UploadFile(directorypath));
     }
     file.SaveAs(directorypath + filename);
     return(filename);
 }
Ejemplo n.º 57
0
    public string saveattachments(string attpath, string reference, System.Web.UI.WebControls.FileUpload fucontrol, string RawUrl)
    {
        //if attpath has had reference appended then don't  probably need to pass reference
        string uploadresult = "";

        if (fucontrol.HasFiles)
        {
            if (!Directory.Exists(attpath))
            {
                Directory.CreateDirectory(attpath);
            }

            if (reference != "")
            {
                reference = "_" + reference;
            }

            int    c1        = 0;
            int    failed    = 0;
            int    succeeded = 0;
            string delim     = "";


            foreach (HttpPostedFile postedFile in fucontrol.PostedFiles)
            {
                c1 = c1 + 1;
                try
                {
                    string wpextension = System.IO.Path.GetExtension(postedFile.FileName);
                    string wpfilename  = System.IO.Path.GetFileNameWithoutExtension(postedFile.FileName);
                    string newfilename = wpfilename + reference + "_" + c1.ToString("000") + wpextension;
                    postedFile.SaveAs(attpath + "\\" + newfilename);
                    uploadresult = uploadresult + delim + System.IO.Path.GetFileName(postedFile.FileName) + "\x00FD" + "Received" + "\x00FD" + newfilename;
                    delim        = "\x00FE";
                    succeeded    = succeeded + 1;
                }
                catch (Exception ex)
                {
                    Log("", RawUrl, ex.Message, "*****@*****.**");
                    uploadresult = uploadresult + delim + System.IO.Path.GetFileName(postedFile.FileName) + "\x00FD" + "Failed" + "\x00FD" + "";
                    delim        = "\x00FE";
                    failed       = failed + 1;
                }
            }
        }
        else
        {
            uploadresult = "File(s) not provided";
        }
        return(uploadresult);
    }
Ejemplo n.º 58
0
    public string File_Upload(System.Web.UI.WebControls.FileUpload fp)
    {
        string filepath, folderpath, savepath, folderpathnew, savepathnew;

        folderpath    = System.Web.HttpContext.Current.Server.MapPath("Resumes");
        folderpathnew = "~\\Resumes";
        filepath      = Path.GetFileName(fp.PostedFile.FileName);
        savepath      = folderpath + "\\" + filepath;

        savepathnew = folderpathnew + "\\" + filepath;

        fp.SaveAs(savepath);
        return(savepathnew);
    }
Ejemplo n.º 59
0
 /// <summary>
 /// 保存文件
 /// </summary>
 /// <param name="file"></param>
 /// <param name="path">文件路径</param>
 /// <returns></returns>
 public static string SaveFile(this System.Web.UI.WebControls.FileUpload file, string path)
 {
     if (file.HasFile)
     {
         FileInfo info     = new FileInfo(file.FileName);
         string   fileName = Guid.NewGuid() + info.Extension;
         file.SaveAs(Path.Combine(path, fileName));
         return(fileName);
     }
     else
     {
         return(string.Empty);
     }
 }
Ejemplo n.º 60
0
        /*------------------------------------------------------------------------------------------------
         *
         * Funksioni i Validimit te skedarit
         * Merr si parameter: kontrollin e skedarit, skedarin dhe username-in)
         * Kontrollon :
         *          -Nese ka skedar te ngarkuar
         *          -Nese skedari ben pjese ne listen tipeve te skedareve te lejuar
         *          -Kerkon nese skedari ekziston tek pathi qe paracaktojm
         * Kthen pergjigje nje string i cili eshte link i dokumentit ne direktorin ku eshte ngarkuar;
         * Emerimi i File:
         *     Koha + file extension [formati i kohes : _MMddyyyy_HHmmss]
         *---------------------*/

        private string Validim_Skedari(HttpPostedFile httpPostedFile, System.Web.UI.WebControls.FileUpload FileUpload1, string User)
        {
            string        Pathi_Dokumenteve = Server.MapPath("../Uploads/Leksione/" + User + "/");
            DirectoryInfo di        = Directory.CreateDirectory(Pathi_Dokumenteve); //Klase qe menaxhon pathet. Nese pathi ekziston nuk en asnje ndryshim ,ne te kundert krijon te gjith folderat e nevojshem
            bool          fileOK    = false;                                        //Tregon Vlefshmerin e dokumentit.Fillimisht eshte false meqenese nuk eshte kryer validimi
            string        extension = "";


            if (FileUpload1.HasFile)
            {
                String   fileExtension     = System.IO.Path.GetExtension(FileUpload1.FileName).ToLower();
                String[] allowedExtensions = { ".doc", ".docx", ".xlsx", ".png", ".jpeg", ".jpg", ".pdf", ".zip", ".rar" };


                for (int i = 0; i < allowedExtensions.Length; i++)
                {
                    if (fileExtension == allowedExtensions[i])
                    {
                        fileOK    = true;
                        extension = fileExtension;
                    }
                }


                if (fileOK)
                {
                    try
                    {
                        string name     = DateTime.UtcNow.ToString("_MMddyyyy_HHmmss") + extension; //Gjenerohet emri me te cilin do te ruhet skedari
                        string filepath = Pathi_Dokumenteve + name;                                 //Pathi i plote fizik
                        FileUpload1.PostedFile.SaveAs(filepath);                                    //Behet ngarkimi i skedarit ne pathin e specifikuar
                        string link_skedari = "../Uploads/Leksione/" + User + "/" + name;           //Krijohet linku i cili do te perdoret me vone ne front end
                        return(link_skedari);
                    }
                    catch (Exception ex)
                    {
                        return("Error Ne Ngarkim");
                        //return ex.Message;
                    }
                }
                else
                {
                    return("Tipi i dokumentit nuk lejohet");
                }
            }
            else
            {
                return("");
            }
        }