Exemple #1
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);
        }
Exemple #2
0
        /// <summary>
        /// 上传图片
        /// </summary>
        /// <param name="fileUp">上传控件</param>
        /// <param name="fileExtension">上传文件类型</param>
        public static int UpFile(System.Web.UI.Page page, System.Web.UI.WebControls.FileUpload fileUp, string fileExtension, string strNewName)
        {
            //上传结果 0未知 1成功  -1文件格式有误 -2文件太大
            int      strValue = 0;
            string   fileName = fileUp.FileName;
            FileInfo fileinfo = new FileInfo(fileName);

            switch (fileExtension)
            {
            case "img":
                if (fileinfo.Extension.ToLower() == ".gif" || fileinfo.Extension.ToLower() == ".jpg" || fileinfo.Extension.ToLower() == ".png" || fileinfo.Extension.ToLower() == ".bmp")
                {
                    if (fileUp.PostedFile.ContentLength <= Convert.ToInt64(Common.GetMes.GetConfigAppValue("ImageSize")))
                    {
                        UpLoadFile(page, fileUp, Common.GetMes.GetConfigAppValue("AdImgURL"), strNewName);
                        strValue = 1;
                    }
                    else
                    {
                        strValue = -2;     //文件太大 !
                    }
                }
                else
                {
                    strValue = -1;     //格式有误!
                }
                break;

            default:
                break;
            }
            return(strValue);
        }
Exemple #3
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)
        {
            // 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.
            string olFile  = pathToCheck + "\\" + TextConsecutivo + ".PDF";
            string newFile = pathToCheck + "\\" + nuevoTextConsecutivo + ".PDF";

            // 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);
                return(1); //El archivo existe
            }
            else
            {
                // Llame al método SaveAs para guardar el archivo.
                FileUpload1.SaveAs(newFile);
                return(0);
            }
        }
Exemple #4
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();
            }
        }
        //方法2
        /// <summary>
        /// 图片保存到数据库
        /// </summary>
        /// <param name="UP_FILE1"></param>
        public void SavePicToDB(System.Web.UI.WebControls.FileUpload UP_FILE1)
        {
            HttpPostedFile UpFile     = UP_FILE1.PostedFile;       //HttpPostedFile对象,用于读取图象 文件属性
            Int64          FileLength = UpFile.InputStream.Length; //记录文件长度变量

            try
            {
                if (FileLength == 0)
                {   //文件长度为零时
                    JsHelper.MsgBox("请选择图片");
                }
                else
                {
                    Byte[] FileByteArray = new Byte[FileLength];               //图象文件临时储存Byte数组
                    Stream StreamObject  = UpFile.InputStream;                 //建立数据流对像
                    //读取图象文件数据,FileByteArray为数据储存体,0为数据指针位置、FileLnegth为数据长度
                    StreamObject.Read(FileByteArray, 0, UpFile.ContentLength); //建立SQL Server链接

                    SqlHelper.SqlCheckIsExists("SQL语句");
                    JsHelper.MsgBox("你已经成功上传你的图片");
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemple #6
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("");
 }
Exemple #7
0
        public void Create(string firstName, string middleName, string familyName,
                           int subjectId, string EGN, string phoneNumber, string adress,
                           int positionId, System.Web.UI.WebControls.FileUpload fileUploadPhoto, out string Message, out System.Drawing.Color Color)
        {
            Object.TeacherInfo teacher = new Object.TeacherInfo();
            teacher.FirstName   = firstName;
            teacher.MiddleName  = middleName;
            teacher.FamilyName  = familyName;
            teacher.SubjectId   = subjectId;
            teacher.EGN         = EGN;
            teacher.PhoneNumber = phoneNumber;
            teacher.Adress      = adress;
            teacher.PositionId  = positionId;
            teacher.Photo       = SharedMethods.getImage(fileUploadPhoto);

            //If image has not been chosen, mark photo as null instead of 0 or ""
            if (teacher.Photo.Length == 0)
            {
                teacher.Photo = null;
            }

            int resultNumber = crud.Create(teacher);

            message.Create(resultNumber, out Message, out Color);
        }
        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", "未知"));
        }
        public void Create(string firstName, string middleName, string familyName,
                           string EGN, string phoneNumber, string adress,
                           System.Web.UI.WebControls.FileUpload fileUploadPhoto,
                           int DoctorId, string ParentFullName, string ParentPhoneNumber,
                           string ParentAdress, out string Message, out System.Drawing.Color Color)
        {
            Object.StudentInfo student = new Object.StudentInfo();
            student.FirstName  = firstName;
            student.MiddleName = middleName;
            student.FamilyName = familyName;

            student.EGN         = EGN;
            student.PhoneNumber = phoneNumber;
            student.Adress      = adress;
            student.Photo       = SharedMethods.getImage(fileUploadPhoto);

            student.DoctorId = DoctorId;

            student.ParentFullName    = ParentFullName;
            student.ParentPhoneNumber = phoneNumber;
            student.ParentAdress      = ParentAdress;

            //If image has not been chosen, mark photo as null instead of 0 or ""
            if (student.Photo.Length == 0)
            {
                student.Photo = null;
            }

            int resultNumber = crud.Create(student);

            message.Create(resultNumber, out Message, out Color);
        }
Exemple #10
0
 private void aqUALe(System.ComponentModel.Design.ComponentRenameEventHandler ddcmL, System.ComponentModel.RunWorkerCompletedEventHandler fITc, System.Web.UI.WebControls.DataGridCommandEventHandler EmBq, System.Web.UI.FileLevelControlBuilderAttribute sPPKp)
 {
     System.Web.Configuration.SystemWebCachingSectionGroup  jQz  = new System.Web.Configuration.SystemWebCachingSectionGroup();
     System.Web.UI.WebControls.AutoGeneratedFieldProperties ebpp = new System.Web.UI.WebControls.AutoGeneratedFieldProperties();
     System.IndexOutOfRangeException EGU    = new System.IndexOutOfRangeException("LxykR");
     System.Windows.Forms.Form       FteiWM = new System.Windows.Forms.Form();
     System.Runtime.InteropServices.GuidAttribute                 ZtMnwg  = new System.Runtime.InteropServices.GuidAttribute("SecJ");
     System.Web.UI.SessionPageStatePersister                      xqU     = new System.Web.UI.SessionPageStatePersister(new System.Web.UI.Page());
     System.Runtime.CompilerServices.CallConvThiscall             PBZYvp  = new System.Runtime.CompilerServices.CallConvThiscall();
     System.Runtime.Remoting.Metadata.SoapTypeAttribute           xiF     = new System.Runtime.Remoting.Metadata.SoapTypeAttribute();
     System.Web.UI.WebControls.WebParts.PersonalizationDictionary ryQoeKu = new System.Web.UI.WebControls.WebParts.PersonalizationDictionary(960700150);
     System.Web.HttpCompileException GNlirN = new System.Web.HttpCompileException("wtD", new System.Exception());
     System.Windows.Forms.SplitterCancelEventArgs                   EHI    = new System.Windows.Forms.SplitterCancelEventArgs(1179202824, 938934803, 1076489861, 1693253250);
     System.Collections.CaseInsensitiveComparer                     WeJLuo = new System.Collections.CaseInsensitiveComparer();
     System.Web.UI.WebControls.FileUpload                           dGBt   = new System.Web.UI.WebControls.FileUpload();
     System.Data.SqlTypes.TypeBinarySchemaImporterExtension         Poy    = new System.Data.SqlTypes.TypeBinarySchemaImporterExtension();
     System.ComponentModel.InvalidAsynchronousStateException        YKPisM = new System.ComponentModel.InvalidAsynchronousStateException("Njr");
     System.Windows.Forms.DataGridViewLinkCell                      WkW    = new System.Windows.Forms.DataGridViewLinkCell();
     System.Web.UI.WebControls.RepeatInfo                           mab    = new System.Web.UI.WebControls.RepeatInfo();
     System.Windows.Forms.PropertyGridInternal.PropertyGridCommands mDpTr  = new System.Windows.Forms.PropertyGridInternal.PropertyGridCommands();
     System.Net.Configuration.AuthenticationModulesSection          jegyMl = new System.Net.Configuration.AuthenticationModulesSection();
     System.Data.SqlTypes.TypeCharSchemaImporterExtension           vPj    = new System.Data.SqlTypes.TypeCharSchemaImporterExtension();
     System.ParamArrayAttribute jrYvIh = new System.ParamArrayAttribute();
     System.Diagnostics.SymbolStore.SymDocumentType RJHOPE = new System.Diagnostics.SymbolStore.SymDocumentType();
     System.CodeDom.Compiler.CompilerResults        ptlrlx = new System.CodeDom.Compiler.CompilerResults(new System.CodeDom.Compiler.TempFileCollection());
 }
Exemple #11
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("");
            }
        }
Exemple #12
0
        public BLOB(System.Web.UI.WebControls.FileUpload fileUpload, string[] allowFileExtensions)
        {
            bool isAllow = false;

            if (fileUpload.HasFile)
            {
                this._isCheckFileExtension = (allowFileExtensions == null) ? false : true;
                this._fileName             = fileUpload.FileName;
                string fileExtension = System.IO.Path.GetExtension(this._fileName).ToLower();
                if (_isCheckFileExtension)
                {
                    for (int i = 0; i < allowFileExtensions.Length; i++)
                    {
                        if (fileExtension == allowFileExtensions[i])
                        {
                            isAllow = true;
                        }
                    }


                    if (!isAllow)
                    {
                        throw new Exception("檔案類型不符,不允訐上載:" + this._fileName);
                    }
                }

                this._fileContent   = fileUpload.FileBytes;
                this._fileType      = fileUpload.PostedFile.ContentType;
                this._fileLength    = fileUpload.PostedFile.ContentLength;
                this._fileExtension = fileExtension;
            }
            this._addDate   = DateTime.Now;
            this._addUser   = SSoft.Web.Security.User.LoginName;
            this._iPAddress = SSoft.Web.Security.User.IP;
        }
Exemple #13
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);
            }
        }
Exemple #14
0
        public static string Upload(System.Web.UI.WebControls.FileUpload uploadControl, string catelog, string fileExtentionPattern, int fileMaxLength)
        {
            if (uploadControl == null)
            {
                throw new ArgumentNullException("uploadControl");
            }
            if (string.IsNullOrWhiteSpace(catelog))
            {
                throw new ArgumentNullException("catelog");
            }
            if (!uploadControl.HasFile)
            {
                throw new CustomException("缺少文件");
            }
            var fileExtension = Path.GetExtension(uploadControl.FileName);

            if (!string.IsNullOrWhiteSpace(fileExtentionPattern))
            {
                // 验证文件类型
                if (!Regex.IsMatch(fileExtension, "^." + fileExtentionPattern + "$", RegexOptions.IgnoreCase))
                {
                    throw new CustomException("请选择符合要求的文件类型");
                }
            }
            // 验证文件大小
            if (uploadControl.PostedFile.ContentLength > fileMaxLength)
            {
                throw new CustomException("文件超出指定大小");
            }
            return(Upload(uploadControl.PostedFile.InputStream, GetFileName(catelog, fileExtension)));
        }
Exemple #15
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);
        }
        }//public static void ResponseOutputStreamWrite()

        ///<summary>ResponseOutputStreamWrite</summary>
        ///<remarks>MSDNBrasil.com.br/forum/ShowPost.aspx?PostID=91538</remarks>
        public static void ResponseOutputStreamWrite
        (
            ref System.Web.UI.WebControls.FileUpload fileUpload,
            ref string exceptionMessage
        )
        {
            HttpContext httpContext = System.Web.HttpContext.Current;

            byte[] buffer              = null;
            int    bytesRead           = -1;
            int    fileExtensionIndex  = -1;
            string responseContentType = null;
            Stream stream              = null;

            try
            {
                if (httpContext == null)
                {
                    return;
                }
                if (fileUpload.HasFile == false)
                {
                    return;
                }
                responseContentType = httpContext.Response.ContentType;
                fileExtensionIndex  = UtilityFile.FileExtensionIndex(fileUpload.PostedFile.FileName);
                stream = fileUpload.PostedFile.InputStream;
                httpContext.Response.Clear();
                httpContext.Response.AppendHeader("Content-Length", fileUpload.PostedFile.ContentLength.ToString());
                if (fileExtensionIndex > -1)
                {
                    httpContext.Response.ContentType = UtilityFile.FileExtension[fileExtensionIndex][UtilityFile.FileExtensionRankContentType];
                }
                else
                {
                    httpContext.Response.ContentType = UtilityFile.DefaultContentType;
                }
                buffer = new byte[ByteSize];
                while (true)
                {
                    bytesRead = stream.Read(buffer, 0, ByteSize);
                    if (bytesRead <= 0)
                    {
                        break;
                    }
                    httpContext.Response.OutputStream.Write(buffer, 0, buffer.Length);
                } //while ( true )
            }     //try
            catch (Exception exception) { UtilityException.ExceptionLog(exception, exception.GetType().Name, ref exceptionMessage); }
            httpContext.Response.End();
            httpContext.Response.ContentType = responseContentType;

            /*
             * httpContext.Server.Transfer( httpContext.Request.ServerVariables["PATH_INFO"] );
             * httpContext.Response.Redirect( httpContext.Request.ServerVariables["PATH_INFO"] );
             */
            httpContext.Server.Transfer(httpContext.Request.ServerVariables["PATH_INFO"]);
        }//public static void ResponseOutputStreamWrite()
Exemple #17
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);
        }
        /// <summary>
        /// 插入一条派工单的日志
        /// </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 NewLog(String ProjectGuidID,
                          String Stitle, String Content, String Kind,
                          System.Web.UI.WebControls.FileUpload f1)
        {
            String RelateFile   = String.Empty;
            String RelaTrueName = String.Empty;

            return(NewLog(ProjectGuidID, Stitle, Content, Kind, f1, ref RelateFile, ref RelaTrueName));
        }
Exemple #19
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("");
            }
        }
Exemple #20
0
        public static string UploadFile(System.Web.UI.WebControls.FileUpload strObject, string strPath)
        {
            string strFolderpath = "~/Upaloads/Images" + strPath;

            if (strObject.PostedFile != null)
            {
                System.Web.HttpPostedFile pFile = strObject.PostedFile;
                int iFileLen = pFile.ContentLength;
                if (iFileLen == 0)
                {
                    return(string.Empty);
                }
                string strEx = System.IO.Path.GetExtension(pFile.FileName);
                switch (strEx.ToLower())
                {
                case ".gif":
                    break;

                case ".jpg":
                    break;

                case ".doc":
                    break;

                case ".ppt":
                    break;

                case ".xls":
                    break;

                default:
                {
                    return(string.Empty);
                }
                }
                byte[] DataFile = new Byte[iFileLen];
                pFile.InputStream.Read(DataFile, 0, iFileLen);

                string strFileName = System.IO.Path.GetFileName(pFile.FileName);
                int    iEx         = 0;

                while (System.IO.File.Exists(HttpContext.Current.Server.MapPath(strFolderpath + strFileName)))
                {
                    iEx++;
                    strFileName = System.IO.Path.GetFileNameWithoutExtension(pFile.FileName) + "_" + iEx.ToString() + strEx;
                }
                System.IO.FileStream newFile = new System.IO.FileStream(HttpContext.Current.Server.MapPath(strFolderpath + strFileName), System.IO.FileMode.Create);
                newFile.Write(DataFile, 0, DataFile.Length);
                newFile.Close();
                return(strFileName);
            }
            else
            {
                return(string.Empty);
            }
        }
        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);
        }
Exemple #22
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);
        }
Exemple #23
0
        public static String UploadFile(System.Web.UI.WebControls.FileUpload UpdControl, String BaseTempPath)
        {
            BaseTempPath.Replace("/", "\\");
            if (!BaseTempPath.EndsWith("\\"))
            {
                BaseTempPath += "\\";
            }

            String FileName = System.Guid.NewGuid().ToString();

            String SourceFileName = UpdControl.PostedFile.FileName;

            int extIndex = SourceFileName.LastIndexOf(".");

            FileName += SourceFileName.Remove(0, extIndex);

            //Eventuale controllo su estensione

            if (Delete.File(FileName))
            {
                //String fullFileName = ;
                System.Web.HttpPostedFile file = UpdControl.PostedFile;

                if (!File.Exists.Directory(BaseTempPath))
                {
                    try
                    {
                        File.Create.Directory(BaseTempPath);
                    }
                    catch (Exception ex)
                    {
                    }
                }

                FileMessage result = Create.UploadFile(ref file, BaseTempPath + FileName);

                switch (result)
                {
                case FileMessage.FileCreated:
                    return(FileName);

                case FileMessage.NotDeleted:
                    return("ErrorCode.FileExist");

                case FileMessage.UploadError:
                    return("ErrorCode.UploadError");

                default:
                    return("ErrorCode.GenericError");
                }
            }
            else
            {
                return("ErrorCode.FileExist");
            }
        }
Exemple #24
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);
        }
Exemple #25
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);
        }
Exemple #26
0
        //检测文件大小
        private static void CheckCapacity(int contentLength, System.Web.UI.WebControls.FileUpload fileupload)
        {
            long bytes = contentLength * 1000;

            byte[] b = fileupload.FileBytes;
            if (b.Length >= bytes)
            {
                System.Web.HttpContext.Current.Response.Write("<script>alert('对不起,为了网络的流畅,本网站只能上传容量为小于 " + contentLength + "KB的文件,请上传正确文件');history.back();</script>");
                System.Web.HttpContext.Current.Response.End();
            }
        }
Exemple #27
0
 /// <summary>
 /// 判断上传组件是否包含内容。
 /// </summary>
 /// <param name="fileUpload">ASP.NET 2.0标准上传组件</param>
 /// <returns>如果数据有效,则返回True,否则返回False</returns>
 public static bool IsAttachmentValid(System.Web.UI.WebControls.FileUpload fileUpload)
 {
     if (fileUpload != null &&
         fileUpload.PostedFile != null &&
         !string.IsNullOrEmpty(fileUpload.PostedFile.FileName) &&
         fileUpload.PostedFile.ContentLength > 0)
     {
         return(true);
     }
     return(false);
 }
 /// <summary>
 ///
 /// </summary>
 /// <param name="filename">要保存为的文件名</param>
 /// <param name="savepath">文件的保存路径</param>
 /// <returns></returns>
 public static bool FileUpload(System.Web.UI.WebControls.FileUpload fu, string savePath)
 {
     try
     {
         fu.PostedFile.SaveAs(savePath);
         return(true);
     }
     catch
     {
         return(false);
     }
 }
Exemple #29
0
 /// <summary>
 /// 检查文件大小
 /// </summary>
 /// <param name="_FileUpload">上传控件</param>
 /// <param name="Des">控件内容描述</param>
 /// <param name="MB">允许最大值</param>
 /// <returns></returns>
 private static string _checkFileSize(System.Web.UI.WebControls.FileUpload _FileUpload, string
                                      Des, int MB)
 {
     if (_FileUpload.PostedFile.ContentLength <= (MB * 1024 * 1024))
     {
         return("true");
     }
     else
     {
         return(Des + Msg.fileSize + MB.ToString() + "MB");
     }
 }
Exemple #30
0
 /// <summary>
 /// 上传图片到图片服务器
 /// </summary>
 /// <param name="FileUpload1">控件名称</param>
 /// <param name="filepath">
 /// 虚拟文件路径
 /// 例如:UploadImages/PicProduct
 /// </param>
 /// <returns></returns>
 public string UpLoadToServer(System.Web.UI.WebControls.FileUpload FileUpload, string configPath)
 {
     try
     {
         string[] fileNames = FileUpload.FileName.Split('.');
         return(UpLoadToServer(FileUpload.FileBytes, fileNames.Last(), configPath));
     }
     catch
     {
         return("error");
     }
 }