Beispiel #1
0
        // Retorna 1 si logro sobreescribir, 0 si no habia archivo, por lo que no sobreecribio, solo creo un nuevo archivo.
        public static int OverWriteFile(System.Web.UI.WebControls.FileUpload FileUpload1, int year, string TextConsecutivo, string nuevoTextConsecutivo, String carpeta)
        {
            // Path del directorio donde vamos a guardar el archivo
            string pathToCheck = path + "" + year;

            pathToCheck = pathToCheck + "\\" + carpeta;
            //Verificamos si existe el directorio, sino existe se crea
            if (!Directory.Exists(pathToCheck))
            {
                Directory.CreateDirectory(pathToCheck);
            }

            // Crear la ruta y el nombre del archivo para comprobar si hay duplicados.
            string olFile  = pathToCheck + "\\" + TextConsecutivo;
            string newFile = pathToCheck + "\\" + nuevoTextConsecutivo;

            // Compruebe si ya existe un archivo con el
            // mismo nombre que el archivo que desea cargar .
            if ((System.IO.File.Exists(olFile)))
            {
                System.IO.File.Move(olFile, newFile);
                System.IO.File.Delete(olFile);
                FileUpload1.SaveAs(newFile);
                return(1); //El archivo existe
            }
            else
            {
                // Llame al método SaveAs para guardar el archivo.
                FileUpload1.SaveAs(newFile);
                return(0);
            }
        }
Beispiel #2
0
        /// <summary>
        /// 文件上传公共类
        /// </summary>
        /// <param name="file">文件</param>
        /// <param name="filePath">保存路径</param>
        /// <param name="enabledFileType">允许文件格式</param>
        /// <param name="maxSize">最大上传大小</param>
        /// <returns>文件名</returns>
        public String UploadFile(System.Web.UI.WebControls.FileUpload file, String filePath, String enabledFileType, Int32 maxSize)
        {
            if (null != file && file.PostedFile.ContentLength > 0)
            {
                String serverPath = System.Web.HttpContext.Current.Server.MapPath(filePath + "/" + DateTime.Now.ToString("yyyy-MM")) + "/";
                if (!System.IO.Directory.Exists(serverPath))
                {
                    System.IO.Directory.CreateDirectory(serverPath);
                }

                String fileExt = file.FileName.Substring(file.FileName.LastIndexOf(".") + 1).ToLower();
                if (!enabledFileType.Contains(fileExt))
                {
                    return("ext_err");  //文件格式错误
                }

                if (maxSize > 0)       //maxSize=0时不限制大小
                {
                    if (file.PostedFile.ContentLength > 5242880)
                    {
                        return("size_err");   //文件大小错误
                    }
                }
                CommOperate cp = new CommOperate();

                String fileName = cp.FileNameMaker() + "." + fileExt;
                file.SaveAs(serverPath + fileName);
                return(DateTime.Now.ToString("yyyy-MM") + "/" + fileName);
            }
            else
            {
                return("");
            }
        }
Beispiel #3
0
        //上传
        private static void FileUpload(System.Web.UI.WebControls.FileUpload fileupload, string file, string imgUri)
        {
            try
            {
                if (System.IO.File.Exists(imgUri))
                {
                    System.Web.HttpContext.Current.Response.Write("<script>alert('此文件已存在,建议重命名后继续上传');if(!confirm('若继续将覆盖原文件,确定继续吗?')){history.back();}</script>");
                    System.IO.File.Delete(imgUri);
                    if (File.Exists(file))
                    {
                        File.Delete(file);
                    }
                }

                fileupload.SaveAs(imgUri);
            }
            catch (Exception)
            {
                System.Web.HttpContext.Current.Response.Write("<script>alert('上传文件操作失败,请刷新页面重试!');history.back();</script>");
                System.Web.HttpContext.Current.Response.End();
            }
            finally
            {
                fileupload.Dispose();
            }
        }
Beispiel #4
0
        public static int SaveFile(System.Web.UI.WebControls.FileUpload FileUpload1, int year, string TextConsecutivo)
        {
            // Obtener el nombre del archivo que desea cargar.
            string archivo = FileUpload1.FileName;
            // Path del directorio donde vamos a guardar el archivo
            string pathToCheck = path + year;

            //Verificamos si existe el directorio, sino existe se crea
            if (!Directory.Exists(pathToCheck))
            {
                Directory.CreateDirectory(pathToCheck);
            }

            // Crear la ruta y el nombre del archivo para comprobar si hay duplicados.
            pathToCheck = pathToCheck + "\\" + TextConsecutivo + ".PDF";
            // Compruebe si ya existe un archivo con el
            // mismo nombre que el archivo que desea cargar .
            if ((System.IO.File.Exists(pathToCheck)))
            {
                return(1); //El archivo existe
            }
            else
            {
                // Llame al método SaveAs para guardar el archivo
                // guardado en el directorio especificado.
                FileUpload1.SaveAs(pathToCheck);
                return(0);
            }
        }
Beispiel #5
0
 public string UploadFile(string uploadPath, System.Web.UI.WebControls.FileUpload fileUpload)
 {
     try
     {
         if (fileUpload.HasFile)
         {
             if (!Directory.Exists(uploadPath))
             {
                 Directory.CreateDirectory(uploadPath);
             }
             string fileName = Guid.NewGuid().ToString() + "_" + fileUpload.FileName;
             string xxx      = uploadPath.Substring(uploadPath.Length - 1);
             if (uploadPath.Substring(uploadPath.Length - 1) != "\\")
             {
                 uploadPath += "\\";
             }
             fileUpload.SaveAs(uploadPath + fileName);
             return(fileName);
         }
     }
     catch (Exception)
     {
     }
     return("");
 }
        public async Task <IHttpActionResult> Upload()
        {
            return(await ResultFactory.Create(ModelState, async arg =>

                                              await Task.Factory.StartNew(() =>
            {
                System.Web.UI.WebControls.FileUpload upload = new System.Web.UI.WebControls.FileUpload();
                string name = upload.FileName;                                                        //获取文件名
                                                                                                      //string name1 = upload.PostedFile.FileName; //获取完整客户端文件路径
                string type = upload.PostedFile.ContentType;                                          //上传文件类型
                                                                                                      //string size = upload.PostedFile.ContentLength.ToString();//上传文件大小
                                                                                                      //string type2 = name.Substring(name.LastIndexOf(".") + 1);//上传文件后缀名
                string ipath = System.Web.HttpContext.Current.Server.MapPath("upload") + "\\" + name; //上传到服务器上后的路径(实际路径),"\\"必须为两个斜杠,在C#中一个斜杠表示转义符.
                string ipath1 = System.Web.HttpContext.Current.Server.MapPath("upload");              //创建文件夹时用
                                                                                                      //string wpath = "upload\\" + name; //虚拟路径
                if (type == "xls" || type == "xlsx" || type == "txt")                                 //根据后缀名来限制上传类型
                {
                    if (!Directory.Exists(ipath1))                                                    //判断文件夹是否已经存在
                    {
                        Directory.CreateDirectory(ipath1);                                            //创建文件夹
                    }
                    upload.SaveAs(ipath);                                                             //上传文件到ipath这个路径里
                }
                return true;
            }), "success", "未知"));
        }
Beispiel #7
0
        /// <summary>
        /// 将客户端的文件上传到服务器
        /// </summary>
        /// <param name="clientFileName"></param>
        /// <returns></returns>
        public static String SaveFileToServer(System.Web.UI.WebControls.FileUpload file1)
        {
            String result = String.Empty;

            try
            {
                if (file1.HasFile)
                {
                    String clientFileName = file1.FileName;
                    String dir1           = "/Attachment/UseAttachment/";

                    HttpServerUtility server1 = System.Web.HttpContext.Current.Server;
                    if (Directory.Exists(server1.MapPath(dir1)) == false)
                    {
                        Directory.CreateDirectory(server1.MapPath(dir1));
                    }
                    String ext = Path.GetExtension(clientFileName);
                    dir1 = dir1 + JString.GetUnique32ID() + ext;

                    file1.SaveAs(server1.MapPath(dir1));
                    result = dir1;
                }
            }
            catch (Exception err)
            {
                result = String.Empty;
            }
            return(result);
        }
Beispiel #8
0
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="fileUpload"></param>
        /// <returns></returns>
        public static bool UploadFile(string strFileName, System.Web.UI.WebControls.FileUpload fileUpload)
        {
            string filename = strFileName != "" ? strFileName : fileUpload.FileName;                      //获取Excel文件名  DateTime日期函数
            string savePath = System.Web.HttpContext.Current.Server.MapPath(("/FileUpload/") + filename); //Server.MapPath 获得虚拟服务器相对路径

            fileUpload.SaveAs(savePath);                                                                  //SaveAs 将上传的文件内容保存在服务器上
            return(true);
        }
Beispiel #9
0
        /// <summary>
        /// 得到周计划的项目明细
        /// </summary>
        /// <param name="f1"></param>
        /// <param name="saveFileName"></param>
        /// <returns></returns>
        public List <Tb_PlanDetailDD> GetWeekPlanDetailListByExcel(System.Web.UI.WebControls.FileUpload f1,
                                                                   ref String saveFileName)
        {
            List <Tb_PlanDetailDD> list1 = new List <Tb_PlanDetailDD>();

            try
            {
                if (f1.HasFile)
                {
                    System.Web.HttpServerUtility server = System.Web.HttpContext.Current.Server;
                    saveFileName = "/Attachment/Plan/" + WebFrame.Util.JString.GetUnique32ID()
                                   + System.IO.Path.GetExtension(f1.FileName);

                    String fname = server.MapPath(saveFileName);
                    UExcel u1    = new UExcel(XlsFormat.Xls2003);
                    f1.SaveAs(fname);
                    DataSet   ds1 = u1.XlsToDataSet(fname);
                    DataTable dt1 = ds1.Tables[0];

                    /*
                     * 分类/编号/计划内容/计划开始时间/计划结束时间/工作量预估(人天)/责任人/交付物/备注
                     */
                    for (int i = 2; i < dt1.Rows.Count; i++)
                    {
                        if (String.IsNullOrEmpty(dt1.Rows[i][1].ToString()) == false &&
                            String.IsNullOrEmpty(dt1.Rows[i][2].ToString()) == false)
                        {
                            Tb_PlanDetailDD dd1 = new Tb_PlanDetailDD();
                            dd1.PlanKind  = dt1.Rows[i][0].ToString();
                            dd1.PlanNum   = dt1.Rows[i][1].ToString();
                            dd1.PlanTitel = dt1.Rows[i][2].ToString();
                            dd1.BegTime   = DateTime.Parse(dt1.Rows[i][3].ToString());
                            dd1.EndTime   = DateTime.Parse(dt1.Rows[i][4].ToString());
                            dd1.Workload  = double.Parse(dt1.Rows[i][5].ToString());

                            //设置责任人
                            String zren1  = dt1.Rows[i][6].ToString();
                            String zrenid = KORWeb.BUL.JUserBU.GetUserIDByUserName(zren1);
                            dd1.ExecuteManID   = zrenid;
                            dd1.ExecuteManName = zren1;

                            dd1.PayMemo = dt1.Rows[i][7].ToString();
                            dd1.Remark  = dt1.Rows[i][8].ToString();

                            dd1.ParentNum     = dd1.PlanNum.Substring(0, 3);    //取前3位
                            dd1.MaonthPlanNum = dd1.PlanNum.Substring(0, 5);    //取前5位

                            list1.Add(dd1);
                        }
                    }
                }
            }
            catch (Exception err)
            {
                list1.Clear();
            }
            return(list1);
        }
Beispiel #10
0
        /// <summary>
        /// Upload a image file, show thumbnail and return the saved path
        /// </summary>
        /// <param name="ctrlFileUpload"></param>
        /// <returns></returns>
        public static string uploadImageFile(
            System.Web.UI.WebControls.FileUpload ctrlFileUpload,  // FileUpload Control
            System.Web.UI.WebControls.Literal litImagePreview,    // Show the upload image
            System.Web.UI.Page page)
        {
            bool   fileOK           = false;
            String fileExtension    = string.Empty;
            string uploadTempFolder = GetTempFolderPath();

            if (ctrlFileUpload.HasFile)
            {
                fileExtension = System.IO.Path.GetExtension(ctrlFileUpload.FileName).ToLower();
                String[] allowedExtensions = { ".jpg", ".png", ".bmp", ".jpeg" };
                for (int i = 0; i < allowedExtensions.Length; i++)
                {
                    if (fileExtension == allowedExtensions[i])
                    {
                        fileOK = true;
                        break;
                    }
                }
            }

            // Check file type
            if (!fileOK)
            {
                string strScript = string.Format("window.setTimeout(\"{0}\", 100);", "alert('仅支持上传图片格式的文件!');");
                page.ClientScript.RegisterClientScriptBlock(typeof(string), "uploadPurposeImage", strScript, true);
                return("");
            }

            // Check length, can't exceed 4M
            if (ctrlFileUpload.FileBytes.Length > 4 * 1024 * 1024)
            {
                string strScript = string.Format("window.setTimeout(\"{0}\", 100);", "alert('文件大小超过限制,请编辑后重试!');");
                page.ClientScript.RegisterClientScriptBlock(typeof(string), "uploadPurposeImage", strScript, true);
                return("");
            }

            try
            {
                string strFileName = Guid.NewGuid().ToString() + fileExtension;
                string strFilePath = uploadTempFolder + strFileName;
                ctrlFileUpload.SaveAs(strFilePath);
                string strScript = string.Format("window.setTimeout(\"{0}\", 100);", "alert('文件上传成功');");
                page.ClientScript.RegisterClientScriptBlock(typeof(string), "uploadPurposeImage", strScript, true);
                //litImagePreview.Text = string.Format("<img width=\"100\" height=\"100\" src=\"/temp/{0}\" />", strFileName);
                ShowThumbnail(litImagePreview, strFileName);
                return(strFilePath);
            }
            catch
            {
                string strScript = string.Format("window.setTimeout(\"{0}\", 100);", "alert('文件上传失败!请重试!');");
                page.ClientScript.RegisterClientScriptBlock(typeof(string), "uploadPurposeImage", strScript, true);
                return("");
            }
        }
Beispiel #11
0
        /// <summary>
        /// 根据计划文件Excel得到计划明细的数据
        /// </summary>
        /// <param name="f1"></param>
        /// <returns></returns>
        public List <Tb_PlanDetailDD> GetPlanDetailListByExcel(System.Web.UI.WebControls.FileUpload f1, ref String saveFileName)
        {
            List <Tb_PlanDetailDD> list1 = new List <Tb_PlanDetailDD>();

            try
            {
                if (f1.HasFile)
                {
                    System.Web.HttpServerUtility server = System.Web.HttpContext.Current.Server;
                    saveFileName = "/Attachment/Plan/" + WebFrame.Util.JString.GetUnique32ID()
                                   + System.IO.Path.GetExtension(f1.FileName);

                    String fname = server.MapPath(saveFileName);
                    UExcel u1    = new UExcel(XlsFormat.Xls2003);
                    f1.SaveAs(fname);
                    DataSet   ds1 = u1.XlsToDataSet(fname);
                    DataTable dt1 = ds1.Tables[0];

                    /*
                     * 分类/编号/计划内容/计划开始时间/计划结束时间/工作量预估(人天)/关键节点/交付物/备注
                     */
                    for (int i = 2; i < dt1.Rows.Count; i++)
                    {
                        if (String.IsNullOrEmpty(dt1.Rows[i][1].ToString()) == false &&
                            String.IsNullOrEmpty(dt1.Rows[i][2].ToString()) == false)
                        {
                            Tb_PlanDetailDD dd1 = new Tb_PlanDetailDD();
                            dd1.PlanKind  = dt1.Rows[i][0].ToString();
                            dd1.PlanNum   = dt1.Rows[i][1].ToString();
                            dd1.PlanTitel = dt1.Rows[i][2].ToString();
                            dd1.BegTime   = DateTime.Parse(dt1.Rows[i][3].ToString());
                            dd1.EndTime   = DateTime.Parse(dt1.Rows[i][4].ToString());
                            dd1.Workload  = double.Parse(dt1.Rows[i][5].ToString());
                            dd1.KeyPlan   = false;
                            if (dt1.Rows[i][6].ToString() != String.Empty)
                            {
                                if (dt1.Rows[i][6].ToString() == "是" || dt1.Rows[i][6].ToString() == "1" ||
                                    dt1.Rows[i][6].ToString().ToLower() == "yes" || dt1.Rows[i][6].ToString().ToLower() == "true")
                                {
                                    dd1.KeyPlan = true;
                                }
                            }
                            dd1.PayMemo = dt1.Rows[i][7].ToString();
                            dd1.Remark  = dt1.Rows[i][8].ToString();

                            list1.Add(dd1);
                        }
                    }
                }
            }
            catch (Exception err)
            {
                list1.Clear();
            }
            return(list1);
        }
        public int NewLog(String ProjectGuidID,
                          String Stitle, String Content, String Kind,
                          System.Web.UI.WebControls.FileUpload f1,
                          ref String RelateFile, ref String RelaTrueName)
        {
            int    succ      = 0;
            String FileDir   = "/Attachment/UseAttachment/";
            String truename1 = String.Empty;
            bool   saveFile  = false;

            try
            {
                Dictionary <String, object> dic1 = new Dictionary <string, object>();

                dic1["guidID"]     = WebFrame.Util.JString.GetUnique32ID();
                dic1["parentGuid"] = ProjectGuidID;
                dic1["Stitle"]     = Stitle;
                if (String.IsNullOrEmpty(Content) == false)
                {
                    dic1["Content"] = (new StringBuilder()).Append(Content);
                }
                dic1["AddTime"]    = DateTime.Now;
                dic1["AddUserID"]  = WebFrame.FrameLib.UserID;
                dic1["AddUserNet"] = WebFrame.FrameLib.UserName;
                dic1["kind"]       = Kind;

                if (f1 != null && f1.HasFile)
                {
                    String ext1 = Path.GetExtension(f1.FileName);
                    truename1 = WebFrame.Util.JString.GetUnique32ID() + ext1;
                    f1.SaveAs(System.Web.HttpContext.Current.Server.MapPath(FileDir + truename1));
                    dic1["RelateFile"]   = FileDir + truename1;
                    dic1["RelaTrueName"] = Path.GetFileName(f1.FileName);

                    //文件名和文件路径
                    RelateFile   = dic1["RelateFile"].ToString();
                    RelaTrueName = dic1["RelaTrueName"].ToString();

                    saveFile = true;
                }
                Tb_Task_LogDA da1 = new Tb_Task_LogDA();
                da1.NewData(dic1);
                succ = 1;
            }
            catch (Exception err)
            {
                //删除已上传的文件
                if (saveFile && File.Exists(System.Web.HttpContext.Current.Server.MapPath(FileDir + truename1)))
                {
                    File.Delete(System.Web.HttpContext.Current.Server.MapPath(FileDir + truename1));
                }
                throw err;
            }

            return(succ);
        }
Beispiel #13
0
        /// <summary>
        /// 插入一条派工单BUG
        /// </summary>
        /// <param name="ProjectGuidID"></param>
        /// <param name="Stitle"></param>
        /// <param name="Content"></param>
        /// <param name="Kind"></param>
        /// <param name="f1"></param>
        /// <returns></returns>
        public int NewBug(String ProjectGuidID,
                          int BugA, int BugB, int BugC, int Kind,
                          String Remark, System.Web.UI.WebControls.FileUpload f1)
        {
            int    succ      = 0;
            String FileDir   = "/Attachment/UseAttachment/";
            String truename1 = String.Empty;
            bool   saveFile  = false;

            try
            {
                Dictionary <String, object> dic1 = new Dictionary <string, object>();

                dic1["guidID"]     = WebFrame.Util.JString.GetUnique32ID();
                dic1["parentGuid"] = ProjectGuidID;

                dic1["BugA"] = BugA;
                dic1["BugB"] = BugB;
                dic1["BugC"] = BugC;

                dic1["Remark"] = Remark;
                dic1["Kind"]   = Kind;

                dic1["AddTime"]    = DateTime.Now;
                dic1["AddUserID"]  = WebFrame.FrameLib.UserID;
                dic1["AddUserNet"] = WebFrame.FrameLib.UserName;

                if (f1 != null && f1.HasFile)
                {
                    String ext1 = Path.GetExtension(f1.FileName);
                    truename1 = WebFrame.Util.JString.GetUnique32ID() + ext1;
                    f1.SaveAs(System.Web.HttpContext.Current.Server.MapPath(FileDir + truename1));
                    dic1["RelateFile"]   = FileDir + truename1;
                    dic1["RelaTrueName"] = Path.GetFileName(f1.FileName);

                    saveFile = true;
                }

                Tb_Task_BugDA da1 = new Tb_Task_BugDA();
                da1.NewData(dic1);
                succ = 1;
            }
            catch (Exception err)
            {
                //删除已上传的文件
                //删除已上传的文件
                if (saveFile && File.Exists(System.Web.HttpContext.Current.Server.MapPath(FileDir + truename1)))
                {
                    File.Delete(System.Web.HttpContext.Current.Server.MapPath(FileDir + truename1));
                }
                throw err;
            }

            return(succ);
        }
Beispiel #14
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="fupAlbumCover">所选择的控件</param>
        /// <param name="fileType">1.图片,2.音频,3.视频,4.office文档,5.歌词</param>
        /// <param name="fileMAXLenth">最大文件</param>
        /// <returns></returns>
        public static string UploadFile(System.Web.UI.WebControls.FileUpload fupAlbumCover, int fileType, int fileMAXLenth)
        {
            string uploadFileName = "";


            if (fupAlbumCover.HasFile)
            {
                if (fupAlbumCover.FileContent.Length < fileMAXLenth * 1024 * 1024)
                {
                    string[] allowedExtension = { ".jpg", ".png", ".bmp", "jpeg", "gif" };
                    switch (fileType)
                    {
                    case 1: allowedExtension = new string[] { ".jpg", ".png", ".bmp", "jpeg", "gif" }; break;

                    case 2: allowedExtension = new string[] { ".mp3", ".wav", ".mid" }; break;

                    case 3: allowedExtension = new string[] { ".mp4", ".wmv", ".flv", "avi", "rmvb" }; break;

                    case 4: allowedExtension = new string[] { ".doc", ".docx", ".xls", "xlsx", "ppt", "pptx" }; break;

                    case 5: allowedExtension = new string[] { ".lrc" }; break;
                    }
                    string uploadedFileExtension = System.IO.Path.GetExtension(fupAlbumCover.FileName).ToLower();
                    bool   isValid = false;
                    foreach (string fileExtension in allowedExtension)
                    {
                        if (uploadedFileExtension == fileExtension)
                        {
                            isValid = true;
                            break;
                        }
                    }
                    if (isValid)
                    {
                        Random r = new Random();
                        uploadFileName = DateTime.Now.ToString("yyyyMMddHHmmss") +
                                         DateTime.Now.Millisecond.ToString() + r.Next(100).ToString() + uploadedFileExtension;
                        fupAlbumCover.SaveAs(HttpContext.Current.Server.MapPath("/UploadFiles/" + uploadFileName));
                    }
                    else
                    {
                        HttpContext.Current.Response.Write("<script>alert('请选择符合格式文件!')</script>");
                    }
                }
                else
                {
                    HttpContext.Current.Response.Write("<script>alert('该文件需小于" + fileMAXLenth + "MB!')</script>");
                }
            }
            else
            {
                HttpContext.Current.Response.Write("<script>alert('请选择一个文件!')</script>");
            }
            return(uploadFileName);
        }
Beispiel #15
0
 /// <summary>
 /// 上传文件
 /// </summary>
 /// <param name="postedFile"></param>
 /// <param name="path"></param>
 /// <param name="filename"></param>
 public void UploadFile(System.Web.UI.WebControls.FileUpload postedFile, string path, string filename)
 {
     #region   文件
     if (Directory.Exists(path) == false)//如果不存在就创建file文件夹
     {
         Directory.CreateDirectory(path);
     }
     if (File.Exists(path + "/" + filename))//如果已经存在此文件就删除该文件
     {
         File.Delete(path + "/" + filename);
     }
     postedFile.SaveAs(path + "/" + filename);//上传文件
     #endregion
 }
Beispiel #16
0
        public static string SavePicture(System.Web.UI.WebControls.FileUpload PictureUpload, System.Web.UI.Page page, string folder)
        {
            string uploedeFileName = PictureUpload.FileName;
            string folderPath      = page.Server.MapPath(folder);

            if (!System.IO.Directory.Exists(folderPath))
            {
                System.IO.Directory.CreateDirectory(folderPath);
            }

            string pName = MyHelper.GenerateProductImageName();
            string pExt  = System.IO.Path.GetExtension(uploedeFileName);
            string pPath = folderPath + pName + pExt;

            PictureUpload.SaveAs(pPath); string s = folder + pName + pExt;

            return(pName + pExt);
        }
Beispiel #17
0
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="page">页面对象</param>
        /// <param name="fileload">上传控件</param>
        /// <param name="strPath">路径</param>
        public static void UpLoadFile(System.Web.UI.Page page, System.Web.UI.WebControls.FileUpload fileload, string strPath, string strNewName)
        {
            string ServerPath = page.Server.MapPath(strPath);

            if (!Directory.Exists(ServerPath))
            {
                //若文件目录不存在 则创建
                Directory.CreateDirectory(ServerPath);
            }
            ServerPath += strNewName;
            try
            {
                fileload.SaveAs(ServerPath);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Beispiel #18
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.PostedFile != null)
                {
                    string fileExtention = Path.GetExtension(FU_Image.FileName.ToLower());
                    if (fileExtention == ".jpeg" || fileExtention == ".jpg" || fileExtention == ".png")
                    {
                        string FileName = Path.GetFileName(FU_Image.PostedFile.FileName);

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

                        FU_Image.SaveAs(System.Web.HttpContext.Current.Server.MapPath("~/pages/news/newsimages/" + rename));

                        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)
            {
            }
        }
Beispiel #19
0
        public ImagemHelper(System.Web.UI.WebControls.FileUpload ObjetoFileUpload)
        {
            #region Valida se o arquivo existe no servidor
            {
                if (!ObjetoFileUpload.HasFile)
                {
                    Erro          = true;
                    ErroDescricao = "Arquivo não foi selecionado";
                    return;
                }
            }
            #endregion

            string extencao = ObjetoFileUpload.FileName.Substring(ObjetoFileUpload.FileName.LastIndexOf('.')).ToLower();

            #region Valida se o arquivo é uma imagem
            {
                if (extencao != ".png" && extencao != ".gif" && extencao != ".jpg" && extencao != ".bmp" && extencao != ".jpeg")
                {
                    Erro          = true;
                    ErroDescricao = "O formato do arquivo não é aceito\\nFormatos aceitos: PNG, GIF, JPG, BMP, JPEG";
                    return;
                }
            }
            #endregion

            #region Grava no diretório temporário
            {
                string raiz = System.Web.HttpContext.Current.Server.MapPath("." + @"\temp\");
                if (!System.IO.Directory.Exists(raiz))
                {
                    System.IO.Directory.CreateDirectory(raiz);
                }

                ImagemOriginal = raiz + DateTime.Now.Ticks.ToString() + extencao;
                ObjetoFileUpload.SaveAs(ImagemOriginal);
            }
            #endregion
        }
Beispiel #20
0
        //#endregion
        //#region 上传文件
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="fileUpload">fileUpload组件</param>
        public void DoUpLoad(System.Web.UI.WebControls.FileUpload fileUpload)
        {
            string __filePath = HttpContext.Current.Server.MapPath(_filePath);

            if (!System.IO.Directory.Exists(__filePath))
            {
                if (_isCreateFolderForNotExits)
                {
                    FileDirectory.DirectoryVirtualCreate(_filePath);
                }
                else
                {
                    _State = 3; return;
                }
            }
            if (fileUpload.PostedFile.ContentLength / 1024 > _maxFileSize)
            {
                _State = 4; return;
            }
            string randStr = "";

            switch (_RandFileType)
            {
            case RandFileType.None: randStr = ""; break;

            case RandFileType.FileName_DateTime: randStr = "_" + Rand.RndDateStr(); break;

            case RandFileType.FileName_RandNumber: randStr = "_" + Rand.RndCode(_RandNumbers); break;

            case RandFileType.DateTime: randStr = Rand.RndDateStr(); break;
            }
            bool isTrue = false;

            if (fileUpload.HasFile)
            {
                string   _fileExt    = System.IO.Path.GetExtension(fileUpload.FileName).ToLower();
                string[] _allowedExt = _allowedExtensions.Split(new string[] { "|" }, StringSplitOptions.None);
                for (int i = 0; i < _allowedExt.Length; i++)
                {
                    if (_fileExt == _allowedExt[i])
                    {
                        isTrue = true;
                    }
                }
                if (isTrue)
                {
                    try {
                        string fNameNoExt = System.IO.Path.GetFileNameWithoutExtension(fileUpload.FileName);
                        if (_RandFileType == RandFileType.DateTime)
                        {
                            fNameNoExt = "";
                        }
                        fileUpload.SaveAs(__filePath + fNameNoExt + randStr + System.IO.Path.GetExtension(fileUpload.FileName));
                        _State    = 0;
                        _fileSize = fileUpload.PostedFile.ContentLength / 1024;
                        _fileName = _filePath + fNameNoExt + randStr + System.IO.Path.GetExtension(fileUpload.FileName);
                    } catch { _State = 2; }
                }
                else
                {
                    _State = 1;
                }
            }
            else
            {
                _State = 2;
            }
        }
 public static void SaveFile(this IContainer container, System.Web.UI.WebControls.FileUpload sender, string filename) =>
     sender.SaveAs(container.GetPath() + filename);