Exemple #1
0
        public static string UploadImage(System.Web.UI.HtmlControls.HtmlInputFile file, string basePath)
        {
            jsHelper js = new jsHelper();

            if (file.PostedFile.ContentLength > 1024 * 1024)
            {
                jsHelper.Alert("上传文件不得大于1M");
                return("");
            }
            if (!file.PostedFile.FileName.ToLower().EndsWith(".jpg"))
            {
                jsHelper.Alert("只能上传jpg图片");
                return("");
            }
            string tempPath = string.Format("{0}/{1}/{2}", DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);

            tempPath = string.Format("{0}/{1}", basePath.TrimEnd(new char[] { '/' }), tempPath);
            string tempFile = string.Format("{0}.jpg", BitConverter.ToUInt32(Guid.NewGuid().ToByteArray(), 0).ToString());
            string fullPath = HttpContext.Current.Server.MapPath(tempPath);

            CDirectory.Create(fullPath);
            file.PostedFile.SaveAs(Path.Combine(fullPath, tempFile));
            string sReturnUrl = string.Format("{0}/{1}", tempPath, tempFile);

            return(sReturnUrl);
        }
Exemple #2
0
        /// <summary>
        /// 上传文件,返回DataTable
        /// </summary>
        /// <param name="inputfile">上传控件</param>
        /// <param name="dt">返回的数据集</param>
        public void ImportData(System.Web.UI.HtmlControls.HtmlInputFile inputfile, ref DataTable dt)
        {
            htmlInputFile = inputfile;
            //得到扩展名
            strFileExtend = inputfile.Value.Substring(htmlInputFile.Value.LastIndexOf(".") + 1);
            //获取导入文件类型
            switch (strFileExtend.Trim().ToUpper())
            {
            case "XLSX":
            case "XLS":
                strServerFileName = SaveServerFile();
                dt = TransformXlsToDataTable();
                break;

            case "CSV":
            case "TXT":
                strServerFileName = SaveServerFile();
                dt = TransformCSVToDataTable();
                break;

            case "":
                throw new Exception("请选择导入文件!");

            default:
                throw new Exception("导入的数据类型不正确!");
            }
        }
Exemple #3
0
        public string Up(System.Web.UI.HtmlControls.HtmlInputFile File2)
        {
            //
            // TODO: 在此处添加构造函数逻辑
            //

            if (File2.PostedFile.ContentLength.ToString() == "0")
            {
                return("上传失败或指定的文件不存在");
            }
            else
            {
                //获取文件名称
                string ss;
                ss = System.DateTime.Now.ToString().Replace("-", "").Replace(" ", "").Replace(":", "") + Path.GetExtension(File2.PostedFile.FileName);
                if (File2.PostedFile.ContentLength / 1024 > 10240)
                {
                    return("您的文件过大,不能上传!");
                }
                else
                {
                    string ty = File2.PostedFile.ContentType;
                    if (ty == "image/gif" || ty == "image/pjpeg")
                    {
                        File2.PostedFile.SaveAs(System.Web.HttpContext.Current.Server.MapPath("~/Uploads/") + ss);
                        return(ss);
                        //Up= ss;
                    }
                    else
                    {
                        return("限制上传!");
                    }
                }
            }
        }
Exemple #4
0
        /// <summary>
        /// 开始上传
        /// </summary>
        /// <param name="inputFile">HtmlInputFile对象</param>
        /// <param name="savePath">要保存的路径</param>
        /// <returns>文件名</returns>
        public string SaveFile(System.Web.UI.HtmlControls.HtmlInputFile inputFile, FileFolderKey fileFolderKey)
        {
            int state = 0;

            this.SetInputFileInfo(inputFile);
            return(this.Save(fileFolderKey.ToString(), string.Empty, ref state));
        }
Exemple #5
0
        public static FileMessage UploadFile(ref System.Web.UI.HtmlControls.HtmlInputFile file, String filePath)
        {
            Impersonate oImpersonate    = new Impersonate();
            Boolean     wasImpersonated = Impersonate.isImpersonated();

            try
            {
                if (!wasImpersonated && oImpersonate.ImpersonateValidUser() == FileMessage.ImpersonationFailed)
                {
                    return(FileMessage.ImpersonationFailed);
                }
                else
                {
                    file.PostedFile.SaveAs(filePath);
                    return(FileMessage.FileCreated);
                }
            }
            catch
            {
                if (!wasImpersonated)
                {
                    oImpersonate.UndoImpersonation();
                }
                return(FileMessage.Catch);
            }
            finally
            {
                if (!wasImpersonated)
                {
                    oImpersonate.UndoImpersonation();
                }
            }
        }
Exemple #6
0
        public static string SaveFile(System.Web.UI.HtmlControls.HtmlInputFile file1, string endfix, System.Web.UI.Page page)
        {
            try
            {
                if (file1.PostedFile != null)
                {
                    string filename;
                    string path = page.Server.MapPath(".\\up\\");
                    if (file1.PostedFile.ContentLength > 0 && file1.PostedFile.ContentLength < 20971520)
                    {
                        filename = System.DateTime.Now.Year.ToString() + System.DateTime.Now.Month.ToString() + System.DateTime.Now.Day.ToString() +
                                   System.DateTime.Now.Hour.ToString() + System.DateTime.Now.Minute.ToString() + System.DateTime.Now.Second.ToString() +
                                   System.DateTime.Now.Millisecond.ToString();

                        filename = path + filename + endfix;
                        file1.PostedFile.SaveAs(filename);
                        return(filename);
                    }
                }
            }
            catch (Exception e)
            {
                //				string c=e.Message;
                return("");
            }
            return("");
        }
        public static byte[] ReadImageFile_Image(System.Web.UI.HtmlControls.HtmlInputFile fl_Image)
        {
            System.Web.UI.HtmlControls.HtmlInputFile img = (System.Web.UI.HtmlControls.HtmlInputFile)fl_Image;
            Byte[] imgByte = null;
            try
            {
                if (img.PostedFile != null)
                {
                    //To create a PostedFile
                    HttpPostedFile File = fl_Image.PostedFile;
                    //Create byte Array with file len
                    imgByte = new Byte[File.ContentLength];
                    //force the control to load data in array
                    File.InputStream.Read(imgByte, 0, File.ContentLength);
                }
                else
                {
                    HttpPostedFile File = fl_Image.PostedFile;
                    imgByte = new Byte[Convert.ToInt32(File.ContentLength)];
                    //imgByte = new Byte[File.ContentLength];
                    File.InputStream.Read(imgByte, 0, File.ContentLength);
                }
            }
            catch (Exception ex)
            {
            }

            return(imgByte);
        }
Exemple #8
0
 /// <summary>
 /// 为HtmlInputFile控件设置值
 /// </summary>
 /// <param name="inputFile">HtmlInputFile对象</param>
 private void SetInputFileInfo(System.Web.UI.HtmlControls.HtmlInputFile inputFile)
 {
     this._inputFile = inputFile;
     this._inputFileContentLength = inputFile.PostedFile.ContentLength;
     this._inputFileName          = inputFile.PostedFile.FileName;
     this._inputFileValue         = inputFile.Value;
 }
Exemple #9
0
        /// <summary>
        /// 开始上传
        /// </summary>
        /// <param name="inputFile">HtmlInputFile对象</param>
        /// <param name="savePath">要保存的路径</param>
        /// <returns>文件名</returns>
        public string SaveFile(System.Web.UI.HtmlControls.HtmlInputFile inputFile, string savePath)
        {
            this.SetInputFileInfo(inputFile);
            int state = 0;

            return(this.Save(savePath, string.Empty, ref state));
        }
Exemple #10
0
        public string upload(System.Web.UI.HtmlControls.HtmlInputFile uploadFiles)
        {
            string p = Server.MapPath("/");

            p = p + "\\data\\";


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

            for (int i = 0; i <= Request.Files.Count - 1; i++)
            {
                //  postedFile = (HttpPostedFile);// Request.Files[i];

                if (Request.Files[i].FileName.Trim().Length > 0)
                {
                    string n = Request.Files[i].FileName.Substring(Request.Files[i].FileName.LastIndexOf("\\") + 1);

                    if (n.EndsWith(".xls"))
                    {
                        Request.Files[i].SaveAs(p + "\\" + n);

                        SaveExcel(p + "\\" + n);
                    }
                }
            }


            return("");
        }
Exemple #11
0
        protected override void CreateChildControls()
        {
            if (_fileUpload == null)
            {
                _fileUpload    = new System.Web.UI.HtmlControls.HtmlInputFile();
                _fileUpload.ID = "upload";
            }

            if (_label == null)
            {
                _label = new System.Web.UI.WebControls.Panel();
            }

            if (_state == null)
            {
                _state    = new System.Web.UI.HtmlControls.HtmlInputHidden();
                _state.ID = "state";
            }

            Controls.Add(_label);
            Controls.Add(_fileUpload);
            Controls.Add(_state);

            base.CreateChildControls();
        }
Exemple #12
0
        public JsonResult uploadImg(System.Web.UI.HtmlControls.HtmlInputFile uploadFiles)
        {
            string p = Server.MapPath("/");

            p = p + "\\upload\\img\\";

            string tmpFile = "";

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

            for (int i = 0; i <= Request.Files.Count - 1; i++)
            {
                if (Request.Files[i].FileName.Trim().Length > 0)
                {
                    string n = Request.Files[i].FileName.Substring(Request.Files[i].FileName.LastIndexOf("\\") + 1);

                    DateTime now = DateTime.Now;
                    DateTime old = new DateTime(2017, 6, 28);
                    TimeSpan ts  = now - old;
                    int      s   = (int)ts.TotalSeconds;
                    Random   r   = new Random();

                    string ext = n.Substring(n.IndexOf("."));
                    n       = s.ToString() + "_" + r.Next(100).ToString() + ext;
                    tmpFile = n;
                    Request.Files[i].SaveAs(p + "\\" + n);
                }
            }


            return(JsonNet(new { url = "/upload/img/" + tmpFile, error = 0 }));
        }
Exemple #13
0
        /// <summary>
        /// 文件上传(变更文件名称)
        /// </summary>
        /// <param name="File2">HtmlInputFile控件</param>
        /// <returns>上传结果</returns>
        public static string FileUpChangeName(System.Web.UI.HtmlControls.HtmlInputFile File2)
        {
            if (File2.PostedFile.ContentLength.ToString() == "0")
            {
                return("上传失败或指定的文件不存在");
            }
            else
            {
                //获取文件名称
                string ss;
                ss = Path.GetExtension(File2.PostedFile.FileName) + System.DateTime.Now.ToString().Replace("-", "").Replace(" ", "").Replace(":", "");

                if (IsSizeAllow(File2.PostedFile.ContentLength.ToString()) == false)
                {
                    return("您的文件过大,不能上传!");
                }
                else
                {
                    string ty = GetFileExp(File2.PostedFile.FileName);
                    if (IsExpAllow(ty) == true)
                    {
                        File2.PostedFile.SaveAs(System.Web.HttpContext.Current.Server.MapPath(CFile.UpDir) + ss);
                        return(ss);
                    }
                    else
                    {
                        return("限制上传!");
                    }
                }
            }
        }
Exemple #14
0
        public string[] EnviarEmailAnexo(string nome, string email, string mensagem, System.Web.UI.HtmlControls.HtmlInputFile anexo)
        {
            MailMessage objEmail = new MailMessage();

            try
            {
                objEmail.From    = ConfigurationSettings.AppSettings["email"].ToString();
                objEmail.Body    = mensagem;
                objEmail.To      = email;
                objEmail.Subject = ConfigurationSettings.AppSettings["subject"].ToString() + nome;
                string caminho = ConfigurationSettings.AppSettings["diretorio"].ToString() + Path.GetFileName(anexo.PostedFile.FileName);
                anexo.PostedFile.SaveAs(caminho);
                objEmail.Attachments.Add(new MailAttachment(caminho));
                SmtpMail.Send(objEmail);
                File.Delete(caminho);
                string[] retorno = new string[2];
                retorno[0] = "1";
                retorno[1] = ConfigurationSettings.AppSettings["confirmacao"].ToString();
                return(retorno);
            }
            catch (Exception erro)
            {
                string[] retorno = new string[2];
                retorno[0] = "0";
                retorno[1] = erro.Message.ToString().Replace("'", "");
                return(retorno);
            }
        }
Exemple #15
0
        public static string UploadFile(System.Web.UI.HtmlControls.HtmlInputFile clientFile, string folderToUp, bool autoGenerateName, bool overwrite, string limitExtension)
        {
            if ((!(clientFile == null)) && (!(clientFile.PostedFile == null)) && !string.IsNullOrEmpty(clientFile.PostedFile.FileName))
            {
                try
                {
                    var postedFile = clientFile.PostedFile;
                    var sFolder    = folderToUp;
                    if (postedFile != null)
                    {
                        //Check exist folder
                        try
                        {
                            if (Directory.Exists(sFolder) == false)
                            {
                                Directory.CreateDirectory(sFolder);
                            }
                        }
                        catch
                        {
                            throw new Exception("Thư mục upload chưa được chỉ định quyền ghi dữ liệu");
                        }

                        //Check validate file extension
                        var fileExtension = Path.GetExtension(postedFile.FileName.ToLower());
                        limitExtension = limitExtension.ToLower();
                        if (limitExtension.IndexOf("*.*") == -1 && limitExtension.IndexOf(fileExtension) == -1)
                        {
                            throw new Exception("Không cho upload định dạng file này");
                        }

                        //Generate file name and check overwrite
                        var fileName = Path.GetFileName(postedFile.FileName);
                        //var sFileName = Path.GetFileNameWithoutExtension(postedFile.FileName);
                        var vFileName = fileName;

                        if (autoGenerateName)
                        {
                            fileName  = fileName.Substring(fileName.LastIndexOf("."));
                            vFileName = fileName.Insert(fileName.LastIndexOf("."), DateTime.Now.ToString("yyyyMMdd_hhmmss"));
                        }

                        vFileName = vFileName.Replace(" ", string.Empty);

                        if (UploadFile(postedFile.InputStream, folderToUp, vFileName, false))
                        {
                            return(vFileName);
                        }
                        throw new Exception("Upload file không thành công!");
                    }
                    return(string.Empty);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            return(string.Empty);
        }
Exemple #16
0
        /// <summary>
        /// 开始上传
        /// </summary>
        /// <param name="inputFile">HtmlInputFile对象</param>
        /// <param name="savePath">要保存的路径</param>
        /// <param name="oldFileName">旧文件名称,便于删除(注:如果存在文件夹路径,程序将自动去除,只留下文件名)</param>
        /// <returns>文件名</returns>
        public string SaveFile(System.Web.UI.HtmlControls.HtmlInputFile inputFile, FileFolderKey fileFolderKey, string oldFileName)
        {
            int state = 0;

            oldFileName = this.ClearFileFolder(oldFileName);
            this.SetInputFileInfo(inputFile);
            return(this.Save(fileFolderKey.ToString(), oldFileName, ref state));
        }
Exemple #17
0
        /// <summary>
        /// 输入上传的控件与存储上传后文件名存放文本控件
        /// 上传文件到指定的信息类型的文件类型,
        /// </summary>
        /// <param name="theUplPic">上传控件</param>
        /// <returns>上传后的文件名</returns>
        public static string UploadFile(System.Web.UI.HtmlControls.HtmlInputFile theUplPic, string UploadServerPath)
        {
            //保证控件存在[没有使用转向链接]]时获得文件名
            string strGetFileName = "";

            try
            {
                strGetFileName = theUplPic.PostedFile.FileName;
            }
            catch
            {
                //上传控件没有找到,或者不可用
                return("");
            }
            //检查文件长度是否为0
            long contentLen = theUplPic.PostedFile.ContentLength;

            if (contentLen == 0)
            {
                return("");
            }
            //没有上传时返回
            if (strGetFileName == "")
            {
                return("");
            }
            int intStartCut = strGetFileName.LastIndexOf(".");

            if (intStartCut < 1)
            {
                return("");
            }
            string strExType = strGetFileName.Substring(intStartCut);

            strExType = strExType.ToLower();
            int ImageContentLength = Convert.ToInt32(ConfigurationManager.AppSettings["AttachContentLength"]); //文件要求的大小

            if (theUplPic.PostedFile.ContentLength < (ImageContentLength * 1024))
            {
                //可以上传
                bool   isFileExist    = true;
                string ServerPath     = "";
                string uploadFileName = "";
                while (isFileExist)
                {
                    uploadFileName = CreatePicName();
                    ServerPath     = UploadServerPath + uploadFileName + strExType;
                    isFileExist    = File.Exists(ServerPath);
                }
                theUplPic.PostedFile.SaveAs(ServerPath);
                return(uploadFileName + strExType);;
            }
            else
            {
                //文件过大
                return("");
            }
        }
Exemple #18
0
        public string uploadItemImage(System.Web.UI.HtmlControls.HtmlInputFile uploadFiles)
        {
            JObject data = new JObject();

            data["add_by"] = CurrentUser.UserId;
            string dish_id = Request.Params["item_id"];
            //string type = Request.Params["t"];

            string p = Server.MapPath("/");

            p = p + "\\upload\\s" + CurrentUser.DepartmentID.ToString() + "\\" + dish_id + "\\";
            string tmpFile = "";

            if (!System.IO.Directory.Exists(p))
            {
                System.IO.Directory.CreateDirectory(p);
            }
            string thumbP = "";

            for (int i = 0; i <= Request.Files.Count - 1; i++)
            {
                if (Request.Files[i].FileName.Trim().Length > 0)
                {
                    string n = Request.Files[i].FileName.Substring(Request.Files[i].FileName.LastIndexOf("\\") + 1);

                    DateTime now = DateTime.Now;
                    DateTime old = new DateTime(2017, 6, 28);
                    TimeSpan ts  = now - old;
                    int      s   = (int)ts.TotalSeconds;
                    Random   r   = new Random();

                    string ext = n.Substring(n.IndexOf("."));
                    n       = s.ToString() + "_" + r.Next(100).ToString() + ext;
                    tmpFile = n;// +"," + tmpFile;
                    Request.Files[i].SaveAs(p + "\\" + n);
                    thumbP = p + "\\thumb\\";
                    if (!System.IO.Directory.Exists(thumbP))
                    {
                        System.IO.Directory.CreateDirectory(thumbP);
                    }
                    ImageClass ic = new ImageClass(p + "\\" + n);
                    ic.GetReducedImage(80, 80, thumbP + "\\" + n);
                }
            }


            // data["image_path"] = tmpFile;
            data["url"]          = "/upload/s" + CurrentUser.DepartmentID.ToString() + "/" + dish_id + "/" + tmpFile;
            data["default_flag"] = 0;
            data["url_thumb"]    = "/upload/s" + CurrentUser.DepartmentID.ToString() + "/" + dish_id + "/thumb/" + tmpFile;;

            runProc(data);


            return(tmpFile);
        }
Exemple #19
0
        /// <summary>
        /// 上传Excel文件
        /// </summary>
        /// <param name="inputfile">上传的控件名</param>
        /// <returns></returns>
        private string UpLoadXls(System.Web.UI.HtmlControls.HtmlInputFile inputfile)
        {
            string orifilename    = string.Empty;
            string uploadfilepath = string.Empty;
            string modifyfilename = string.Empty;
            string fileExtend     = ""; //文件扩展名
            int    fileSize       = 0;  //文件大小

            try
            {
                if (inputfile.Value != string.Empty)
                {
                    //得到文件的大小
                    fileSize = inputfile.PostedFile.ContentLength;
                    if (fileSize == 0)
                    {
                        throw new Exception("导入的Excel文件大小为0,请检查是否正确!");
                    }
                    //得到扩展名
                    fileExtend = inputfile.Value.Substring(inputfile.Value.LastIndexOf(".") + 1);
                    //if (fileExtend.ToLower() != "xls")
                    //{
                    //    throw new Exception("你选择的文件格式不正确,只能导入EXCEL文件!");
                    //}
                    //路径
                    uploadfilepath = Server.MapPath("~/impExcel");
                    //新文件名
                    modifyfilename  = System.Guid.NewGuid().ToString();
                    modifyfilename += "." + inputfile.Value.Substring(inputfile.Value.LastIndexOf(".") + 1);
                    //判断是否有该目录
                    System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(uploadfilepath);
                    if (!dir.Exists)
                    {
                        dir.Create();
                    }
                    orifilename = uploadfilepath + "\\" + modifyfilename;
                    //如果存在,删除文件
                    if (File.Exists(orifilename))
                    {
                        File.Delete(orifilename);
                    }
                    // 上传文件
                    inputfile.PostedFile.SaveAs(orifilename);
                }
                else
                {
                    throw new Exception("请选择要导入的Excel文件!");
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(orifilename);
        }
Exemple #20
0
        /// <summary>
        /// 检查等待上传的图片是否符合要求
        /// </summary>
        /// <param name="theUplPic"></param>
        /// <returns></returns>
        public static int checkUploadFile(System.Web.UI.HtmlControls.HtmlInputFile theUplPic)
        {
            //保证控件存在[没有使用转向链接]]时获得文件名
            string strGetFileName = "";

            try
            {
                strGetFileName = theUplPic.PostedFile.FileName;
            }
            catch
            {
                //上传控件没有找到,或者不可用
                return(3);
            }

            if (strGetFileName == "")
            {
                //没有上传图片
                return(3);
            }
            //检查文件长度是否为0
            long contentLen = theUplPic.PostedFile.ContentLength;

            if (contentLen == 0)
            {
                return(3);
            }
            int intStartCut = strGetFileName.LastIndexOf(".");

            if (intStartCut < 1)
            {
                return(3);
            }
            string strExType = strGetFileName.Substring(intStartCut);

            strExType = strExType.ToLower();
            if (strExType == ".gif" || strExType == ".jpg")
            {
                int ImageContentLength = Convert.ToInt32(ConfigurationManager.AppSettings["ImageContentLength"]); //文件要求的大小
                if (theUplPic.PostedFile.ContentLength < (ImageContentLength * 1024))
                {
                    return(0);
                }
                else
                {
                    //文件过大
                    return(1);
                }
            }
            else
            {
                //文件过大
                return(2);
            }
        }
Exemple #21
0
        public string UploadFile(string filePath, int maxSize, string[] fileType, System.Web.UI.HtmlControls.HtmlInputFile TargetFile)
        {
            string Result = "UnDefine";
            bool   typeFlag = false;
            string FilePath = filePath;
            int    MaxSize = maxSize;
            string strFileName, strNewName, strFilePath;

            if (TargetFile.PostedFile.FileName == "")
            {
                return("FILE_ERR");
            }
            strFileName       = TargetFile.PostedFile.FileName;
            TargetFile.Accept = "*/*";
            strFilePath       = FilePath;
            if (Directory.Exists(strFilePath) == false)
            {
                Directory.CreateDirectory(strFilePath);
            }
            FileInfo myInfo     = new FileInfo(strFileName);
            string   strOldName = myInfo.Name;

            strNewName = strOldName.Substring(strOldName.LastIndexOf("."));
            strNewName = strNewName.ToLower();
            if (TargetFile.PostedFile.ContentLength <= MaxSize)
            {
                for (int i = 0; i <= fileType.GetUpperBound(0); i++)
                {
                    if (strNewName.ToLower() == fileType[i].ToString())
                    {
                        typeFlag = true; break;
                    }
                }
                if (typeFlag)
                {
                    string strFileNameTemp = GetUploadFileName();
                    string strFilePathTemp = strFilePath;
                    float  strFileSize     = TargetFile.PostedFile.ContentLength;
                    strOldName  = strFileNameTemp + strNewName;
                    strFilePath = strFilePath + "\\" + strOldName;
                    TargetFile.PostedFile.SaveAs(strFilePath);
                    Result = strOldName + "|" + strFileSize;
                    TargetFile.Dispose();
                }
                else
                {
                    return("TYPE_ERR");
                }
            }
            else
            {
                return("SIZE_ERR");
            }
            return(Result);
        }
Exemple #22
0
        /// <summary>
        /// 上传Excel文件
        /// </summary>
        /// <param name="inputfile">上传的控件名</param>
        /// <returns></returns>
        private string UpLoadXls(System.Web.UI.HtmlControls.HtmlInputFile inputfile)
        {
            string orifilename    = string.Empty;
            string uploadfilepath = string.Empty;
            string modifyfilename = string.Empty;
            string fileExtend     = ""; //文件扩展名
            int    fileSize       = 0;  //文件大小

            try
            {
                if (inputfile.Value != string.Empty)
                {
                    //得到文件的大小
                    fileSize = inputfile.PostedFile.ContentLength;
                    if (fileSize == 0)
                    {
                        throw new Exception(App_GlobalResources.Language.Tip_UploadExcelIsEmpty);
                    }
                    //得到扩展名
                    fileExtend = inputfile.Value.Substring(inputfile.Value.LastIndexOf(".") + 1);
                    if (fileExtend.ToLower() != "xls" && fileExtend.ToLower() != "csv" && fileExtend.ToLower() != "xlsx")
                    {
                        throw new Exception(App_GlobalResources.Language.Tip_LimitImportOnlyExcel);
                    }
                    //路径
                    uploadfilepath = Server.MapPath("~/UpFiles");
                    //新文件名
                    modifyfilename  = System.Guid.NewGuid().ToString();
                    modifyfilename += "." + inputfile.Value.Substring(inputfile.Value.LastIndexOf(".") + 1);
                    //判断是否有该目录
                    System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(uploadfilepath);
                    if (!dir.Exists)
                    {
                        dir.Create();
                    }
                    orifilename = uploadfilepath + "\\" + modifyfilename;
                    //如果存在,删除文件
                    if (File.Exists(orifilename))
                    {
                        File.Delete(orifilename);
                    }
                    // 上传文件
                    inputfile.PostedFile.SaveAs(orifilename);
                }
                else
                {
                    throw new Exception(App_GlobalResources.Language.Tip_PleaseSelectImportExcel);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(orifilename);
        }
Exemple #23
0
 /// <summary>
 /// 上传图片到图片服务器
 /// </summary>
 /// <param name="FileUpload1">控件名称</param>
 /// <param name="filepath">
 /// 虚拟文件路径
 /// 例如:UploadImages/PicProduct
 /// </param>
 /// <returns></returns>
 public string UpLoadToServer(System.Web.UI.HtmlControls.HtmlInputFile InputFile, Page page)
 {
     try
     {
         string[] fileNames = InputFile.PostedFile.FileName.Split('.');
         return(UpLoadToServer(GetImageToByteArray(InputFile.PostedFile), fileNames.Last(), page));
     }
     catch
     {
         return("error");
     }
 }
Exemple #24
0
        /// <summary>
        /// 上传图片返回 0则超过规定大小;1文件格式错误;
        /// </summary>
        /// <param name="files">文件框名称</param>
        /// <param name="paths">上传文件路径,url</param>
        /// <param name="fmax">文件的最大值,单位为字节</param>
        /// <param name="ftype">类型:1表示图片;0表示所有文件</param>
        /// <returns></returns>
        public static string upfiles(System.Web.UI.HtmlControls.HtmlInputFile files, string paths, long fmax, string ftype, string fileName)
        {
            //files 文件上传组件的名称;paths 要上传到的目录;fmax是上传文件最大值;ftype是上传文件的类型
            //默认上传文件最大值100k,文件类型为所有文件
            //1为图片jpg or gif;0为所有文件
            //如果文件大于设定值,返回代码0
            //如果文件类型错误,返回代码1
            //初始化
            long   fileMax   = 100000;
            string fileType  = "0";
            string fileTypet = "";

            fileMax  = fmax;
            fileType = ftype;



            if (files.PostedFile.ContentLength > fileMax)
            {
                return("0");
                //返回错误代码,结束程序
            }

            fileTypet = System.IO.Path.GetExtension(files.PostedFile.FileName).ToLower();
            if (fileType == "1")
            {
                if (fileTypet != ".jpg" && fileTypet != ".jpeg" && fileTypet != ".gif")
                {
                    return("1");
                    //返回错误代码,结束程序
                }
            }
            string destdir = System.Web.HttpContext.Current.Server.MapPath(paths);

            if (!Directory.Exists(destdir))
            {
                Directory.CreateDirectory(destdir);
            }
            string filename = fileName + fileTypet;
            string destpath = System.IO.Path.Combine(destdir, filename);

            //检查是否有名称重复,如果重复就在前面加从0开始的数字
            int    i            = 0;
            string tempfilename = filename;

            //没有重复,保存文件
            files.PostedFile.SaveAs(destpath);
            //返回文件名称
            return(tempfilename);
        }
Exemple #25
0
        public List <clsXmlFileInfo> ExtractZip(System.Web.UI.HtmlControls.HtmlInputFile oHtmlInputFile)
        {
            string zipFileName = Path.GetFileName(oHtmlInputFile.PostedFile.FileName);

            zipFileName = zipFileName.Replace(Path.GetExtension(oHtmlInputFile.PostedFile.FileName), "");

            string[] Val = zipFileName.Split('_');

            string sPassword = Val[0] + "" + Val[1];

            inputStream = new ZipInputStream(oHtmlInputFile.PostedFile.InputStream);

            inputStream.Password = sPassword;
            List <clsXmlFileInfo> oListXmlFileInfo = new List <clsXmlFileInfo>();

            try
            {
                int            size         = 2048;
                byte[]         data         = new byte[2048];
                clsXmlFileInfo oXmlFileInfo = null;
                StringBuilder  oS           = new StringBuilder();
                ZipEntry       entry;
                while ((entry = inputStream.GetNextEntry()) != null)
                {
                    oXmlFileInfo             = new clsXmlFileInfo();
                    oXmlFileInfo.XmlFileName = entry.Name;
                    while (true)
                    {
                        size = inputStream.Read(data, 0, data.Length);
                        if (size > 0)
                        {
                            oS.Append(new ASCIIEncoding().GetString(data, 0, size));
                        }
                        else
                        {
                            break;
                        }
                    }

                    oXmlFileInfo.XmlData = oS.ToString();
                    oListXmlFileInfo.Add(oXmlFileInfo);
                    oS.Remove(0, oS.ToString().Length);
                }
            }
            finally
            {
                inputStream.Close();
            }
            return(oListXmlFileInfo);
        }
Exemple #26
0
        public string uploadImage(System.Web.UI.HtmlControls.HtmlInputFile uploadFiles)
        {
            string p = Server.MapPath("/");

            p = p + "\\upload\\";
            string tmpFile = "";

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

            for (int i = 0; i <= Request.Files.Count - 1; i++)
            {
                if (Request.Files[i].FileName.Trim().Length > 0)
                {
                    string n = Request.Files[i].FileName.Substring(Request.Files[i].FileName.LastIndexOf("\\") + 1);

                    DateTime now = DateTime.Now;
                    DateTime old = new DateTime(2017, 6, 28);
                    TimeSpan ts  = now - old;
                    int      s   = (int)ts.TotalSeconds;
                    Random   r   = new Random();

                    string ext = n.Substring(n.IndexOf("."));
                    n       = s.ToString() + "_" + r.Next(100).ToString() + ext;
                    tmpFile = n + "," + tmpFile;
                    Request.Files[i].SaveAs(p + "\\" + n);
                    string thumbP = p + "\\thumb\\";
                    if (!System.IO.Directory.Exists(thumbP))
                    {
                        System.IO.Directory.CreateDirectory(thumbP);
                    }
                    ImageClass ic = new ImageClass(p + "\\" + n);
                    ic.GetReducedImage(80, 80, thumbP + "\\" + n);
                    //if (n.EndsWith(".xls"))
                    //{

                    //    Request.Files[i].SaveAs(p + "\\" + n);

                    //    SaveExcel(p + "\\" + n);

                    //}
                }
            }


            return(Request.Params["testid"] + ";" + tmpFile);
        }
Exemple #27
0
        /// <summary>
        /// Get The byte By HtmlInputFile.
        /// </summary>
        /// <param name="fileControl">HtmlInputFile</param>
        /// <returns>byte</returns>
        public static byte[] GetByteByHtmlInputFile(System.Web.UI.HtmlControls.HtmlInputFile FileUpload1)
        {
            //获得转化后的字节数组
            //得到用户要上传的文件名
            string strFilePathName = FileUpload1.PostedFile.FileName;
            string strFileName     = Path.GetFileName(strFilePathName);
            int    FileLength      = FileUpload1.PostedFile.ContentLength;
            //上传文件
            var FileByteArray = new Byte[FileLength];               //图象文件临时储存Byte数组
            var StreamObject  = FileUpload1.PostedFile.InputStream; //建立数据流对像

            //读取图象文件数据,FileByteArray为数据储存体,0为数据指针位置、FileLnegth为数据长度
            StreamObject.Read(FileByteArray, 0, FileLength);
            return(FileByteArray);
        }
Exemple #28
0
 /// <summary>
 /// 修改上传的文件
 /// </summary>
 /// <param name="ffFile"></param>
 /// <param name="strAbsolutePath"></param>
 /// <param name="strOldFileName"></param>
 /// <returns></returns>
 public static string CoverFile(System.Web.UI.HtmlControls.HtmlInputFile ffFile, string strAbsolutePath, string strOldFileName)
 {
     if (ffFile.PostedFile.FileName != string.Empty)
     {
         if (strOldFileName != string.Empty)
         {
             DeleteFile(strOldFileName, strAbsolutePath);
         }
         return(UpLoadFile(ffFile, strAbsolutePath));
     }
     else
     {
         throw new Exception("文件不存在,无法上传!");
     }
 }
Exemple #29
0
        /// <summary>
        /// 上传word文件到服务器
        /// </summary>
        /// <param name="uploadFiles"></param>
        /// <returns></returns>
        public string uploadWord(System.Web.UI.HtmlControls.HtmlInputFile uploadFiles)
        {
            string FilePath;
            string newName = "";

            if (uploadFiles.PostedFile != null)
            {
                string fileName        = uploadFiles.PostedFile.FileName;
                int    extendNameIndex = fileName.LastIndexOf(".");
                string extendName      = fileName.Substring(extendNameIndex);
                try
                {
                    //验证是否为word格式
                    if (extendName == ".doc" || extendName == ".docx")
                    {
                        DateTime now = DateTime.Now;
                        newName = now.DayOfYear.ToString() + uploadFiles.PostedFile.ContentLength.ToString();
                        // 判断指定目录下是否存在文件夹,如果不存在,则创建
                        FilePath = Server.MapPath("~\\wordTmp");
                        if (!Directory.Exists(FilePath))
                        {
                            // 创建up文件夹
                            Directory.CreateDirectory(Server.MapPath("~\\wordTmp"));
                        }
                        //上传路径 指当前上传页面的同一级的目录下面的wordTmp路径
                        string str = Server.MapPath("wordTmp/" + newName + extendName);
                        Alert.Show("word路径" + str);
                        //Page.ClientScript.RegisterStartupScript(this.GetType(), "message", "alert(" + str + ")", true);
                        uploadFiles.PostedFile.SaveAs(FilePath + "\\" + newName + extendName);
                    }
                    else
                    {
                        return("1");
                    }
                }
                catch
                {
                    return("0");
                }
                //www.2cto.com
                //return "http://" + HttpContext.Current.Request.Url.Host + HttpContext.Current.Request.ApplicationPath + "/wordTmp/" + newName + extendName;
                return(FilePath + "\\" + newName + extendName);
            }
            else
            {
                return("0");
            }
        }
Exemple #30
0
        public static string UploadFile(System.Web.UI.HtmlControls.HtmlInputFile clientFile, string strFileName, string folderToUp, bool overwrite, string limitExtension)
        {
            if ((!(clientFile == null)) && (!(clientFile.PostedFile == null)) && !string.IsNullOrEmpty(clientFile.PostedFile.FileName))
            {
                try
                {
                    var postedFile = clientFile.PostedFile;
                    //string ContentTypeFile = postedFile.ContentType;

                    if (postedFile != null)
                    {
                        var sFolder = folderToUp;
                        try
                        {
                            if (Directory.Exists(sFolder) == false)
                            {
                                Directory.CreateDirectory(sFolder);
                            }
                        }
                        catch
                        {
                            return(string.Empty);
                        }


                        //Check validate file extension
                        var fileExtension = Path.GetExtension(postedFile.FileName.ToLower());
                        limitExtension = limitExtension.ToLower();
                        if (limitExtension.IndexOf("*.*") == -1 && limitExtension.IndexOf(fileExtension) == -1)
                        {
                            return("");
                        }

                        var vFileName = strFileName;

                        UploadFile(postedFile.InputStream, folderToUp, vFileName, overwrite);
                        return(vFileName);
                    }
                    return(string.Empty);
                }
                catch
                {
                    return(string.Empty);
                }
            }
            return(string.Empty);
        }
Exemple #31
0
 /// <summary>
 /// 上传文件,返回DataTable
 /// </summary>
 /// <param name="inputfile">上传控件</param>
 /// <param name="dt">返回的数据集</param>
 public void ImportData(System.Web.UI.HtmlControls.HtmlInputFile inputfile, ref DataTable dt)
 {
     htmlInputFile = inputfile;
     //得到扩展名
     strFileExtend = inputfile.Value.Substring(htmlInputFile.Value.LastIndexOf(".") + 1);
     //获取导入文件类型
     switch (strFileExtend.Trim().ToUpper())
     {
         case "XLSX":
         case "XLS":
             strServerFileName = SaveServerFile();
             dt = TransformXlsToDataTable();
             break;
         case "CSV":
         case "TXT":
             strServerFileName = SaveServerFile();
             dt = TransformCSVToDataTable();
             break;
         case "":
             throw new Exception("请选择导入文件!");
         default:
             throw new Exception("导入的数据类型不正确!");
     }
 }
Exemple #32
0
        /// <summary>
        /// 
        /// </summary>
        protected void mainInterface( anmar.SharpWebMail.CTNInbox inbox )
        {
            this.newattachmentPH=(System.Web.UI.WebControls.PlaceHolder )this.SharpUI.FindControl("newattachmentPH");
            this.attachmentsPH=(System.Web.UI.WebControls.PlaceHolder )this.SharpUI.FindControl("attachmentsPH");
            this.confirmationPH=(System.Web.UI.WebControls.PlaceHolder )this.SharpUI.FindControl("confirmationPH");
            this.newMessagePH=(System.Web.UI.WebControls.PlaceHolder )this.SharpUI.FindControl("newMessagePH");
            this.newMessageWindowAttachFile=( System.Web.UI.HtmlControls.HtmlInputFile )this.SharpUI.FindControl("newMessageWindowAttachFile");
            this.newMessageWindowAttachmentsList=(System.Web.UI.WebControls.CheckBoxList )this.SharpUI.FindControl("newMessageWindowAttachmentsList");
            this.newMessageWindowAttachmentsAddedList=(System.Web.UI.WebControls.DataList )this.SharpUI.FindControl("newMessageWindowAttachmentsAddedList");

            this.FCKEditor = (FredCK.FCKeditorV2.FCKeditor)this.SharpUI.FindControl("FCKEditor");
            this.fromname = (System.Web.UI.HtmlControls.HtmlInputText)this.SharpUI.FindControl("fromname");
            this.fromemail = (System.Web.UI.HtmlControls.HtmlInputText)this.SharpUI.FindControl("fromemail");
            this.subject = (System.Web.UI.HtmlControls.HtmlInputText)this.SharpUI.FindControl("subject");
            this.toemail = (System.Web.UI.HtmlControls.HtmlInputText)this.SharpUI.FindControl("toemail");

            #if MONO
            System.Web.UI.WebControls.RequiredFieldValidator rfv = (System.Web.UI.WebControls.RequiredFieldValidator) this.SharpUI.FindControl("ReqbodyValidator");
            rfv.Enabled=false;
            this.Validators.Remove(rfv);
            #endif

            this.newMessageWindowConfirmation = (System.Web.UI.WebControls.Label)this.SharpUI.FindControl("newMessageWindowConfirmation");

            this.SharpUI.refreshPageImageButton.Click += new System.Web.UI.ImageClickEventHandler(refreshPageButton_Click);

            // Disable PlaceHolders
            this.attachmentsPH.Visible = false;
            this.confirmationPH.Visible = false;

            // Disable some things
            this.SharpUI.nextPageImageButton.Enabled = false;
            this.SharpUI.prevPageImageButton.Enabled = false;
            // Get mode
            if ( Page.Request.QueryString["mode"]!=null ) {
                try {
                    this._message_mode = (anmar.SharpWebMail.UI.MessageMode)System.Enum.Parse(typeof(anmar.SharpWebMail.UI.MessageMode), Page.Request.QueryString["mode"], true);
                } catch ( System.Exception ){}
            }
            // Get message ID
            System.String msgid = System.Web.HttpUtility.HtmlEncode (Page.Request.QueryString["msgid"]);
            System.Guid guid = System.Guid.Empty;
            if ( msgid!=null )
                guid = new System.Guid(msgid);
            if ( !this.IsPostBack && !guid.Equals( System.Guid.Empty) ) {
                System.Object[] details = inbox[ guid ];
                if ( details!=null ) {
                    if ( this._message_mode.Equals(anmar.SharpWebMail.UI.MessageMode.None) )
                        this._message_mode = anmar.SharpWebMail.UI.MessageMode.reply;
                    this._headers = (anmar.SharpMimeTools.SharpMimeHeader) details[13];
                    if ( !this.IsPostBack ) {
                        bool html_content = this.FCKEditor.CheckBrowserCompatibility();

                        this.subject.Value = System.String.Concat (this.SharpUI.LocalizedRS.GetString(System.String.Concat(this._message_mode, "Prefix")), ":");
                        if ( details[10].ToString().ToLower().IndexOf (this.subject.Value.ToLower())!=-1 ) {
                            this.subject.Value = details[10].ToString().Trim();
                        } else {
                            this.subject.Value = System.String.Concat (this.subject.Value, " ", details[10]).Trim();
                        }
                        // Get the original message
                        inbox.CurrentFolder = details[18].ToString();
                        System.IO.MemoryStream ms = inbox.GetMessage((int)details[1], msgid);
                        anmar.SharpMimeTools.SharpMessage message = null;
                        if ( ms!=null && ms.CanRead ) {
                            System.String path = null;
                            if ( this._message_mode.Equals(anmar.SharpWebMail.UI.MessageMode.forward) ) {
                                path = Session["sharpwebmail/read/message/temppath"].ToString();
                                path = System.IO.Path.Combine (path, msgid);
                                path = System.IO.Path.GetFullPath(path);
                            }
                            bool attachments = false;
                            if ( this._message_mode.Equals(anmar.SharpWebMail.UI.MessageMode.forward) )
                                attachments = (bool)Application["sharpwebmail/send/message/forwardattachments"];
                            message = new anmar.SharpMimeTools.SharpMessage(ms, attachments, html_content, path);
                        }
                        if ( this._message_mode.Equals(anmar.SharpWebMail.UI.MessageMode.reply) ) {
                            // From name if present on original message's To header
                            // and we don't have it already
                            if ( Session["DisplayName"]==null ) {
                                foreach ( anmar.SharpMimeTools.SharpMimeAddress address in (System.Collections.IEnumerable) details[8] ) {
                                    if ( address["address"]!=null && address["address"].Equals( User.Identity.Name )
                                        && address["name"].Length>0 && !address["address"].Equals(address["name"]) ) {
                                        this.fromname.Value = address["name"];
                                        break;
                                    }
                                }
                            }
                            // To addresses
                            foreach ( anmar.SharpMimeTools.SharpMimeAddress address in (System.Collections.IEnumerable) details[9] ) {
                                if ( address["address"]!=null && !address["address"].Equals( User.Identity.Name ) ) {
                                    if ( this.toemail.Value.Length >0 )
                                        this.toemail.Value += ", ";
                                    this.toemail.Value += address["address"];
                                }
                            }
                        } else if ( this._message_mode.Equals(anmar.SharpWebMail.UI.MessageMode.forward) ) {
                            // If the original message has attachments, preserve them
                            if ( message!=null && message.Attachments!=null &&  message.Attachments.Count>0 ) {
                                this.bindAttachments();
                                foreach ( anmar.SharpMimeTools.SharpAttachment attachment in message.Attachments ) {
                                    if ( attachment.SavedFile==null )
                                        continue;
                                    this.AttachmentSelect(System.IO.Path.Combine(attachment.SavedFile.Directory.Name, attachment.SavedFile.Name));
                                }
                                this.Attach_Click(this, null);
                            }
                        }
                        // Preserve the original body and some properties
                        if ( message!=null ) {
                            System.Text.StringBuilder sb_body = new System.Text.StringBuilder();
                            System.String line_end = null;
                            if ( html_content )
                                line_end = "<br />\r\n";
                            else
                                line_end = "\r\n";
                            sb_body.Append(this.SharpUI.LocalizedRS.GetString(System.String.Concat(this._message_mode, "PrefixBody")));
                            sb_body.Append(line_end);
                            sb_body.Append(this.SharpUI.LocalizedRS.GetString("newMessageWindowFromNameLabel"));
                            sb_body.Append(" ");
                            sb_body.Append(message.From);
                            sb_body.Append(" [mailto:");
                            sb_body.Append(message.FromAddress);
                            sb_body.Append("]");
                            sb_body.Append(line_end);
                            sb_body.Append(this.SharpUI.LocalizedRS.GetString("newMessageWindowDateLabel"));
                            sb_body.Append(" ");
                            sb_body.Append(message.Date.ToString());
                            sb_body.Append(line_end);
                            sb_body.Append(this.SharpUI.LocalizedRS.GetString("newMessageWindowToEmailLabel"));
                            sb_body.Append(" ");
                            if ( html_content )
                                sb_body.Append(System.Web.HttpUtility.HtmlEncode(message.To.ToString()));
                            else
                                sb_body.Append(message.To);
                            sb_body.Append(line_end);
                            sb_body.Append(this.SharpUI.LocalizedRS.GetString("newMessageWindowSubjectLabel"));
                            sb_body.Append(" ");
                            sb_body.Append(message.Subject);
                            sb_body.Append(line_end);
                            sb_body.Append(line_end);
                            if ( !message.HasHtmlBody &&  html_content )
                                sb_body.Append("<pre>");
                            sb_body.Append(message.Body);
                            if ( !message.HasHtmlBody &&  html_content )
                                sb_body.Append("</pre>");
                            if ( this._message_mode.Equals(anmar.SharpWebMail.UI.MessageMode.reply) ) {
                                if ( html_content ) {
                                    sb_body.Insert(0, System.String.Concat("<blockquote style=\"", Application["sharpwebmail/send/message/replyquotestyle"] ,"\">"));
                                    sb_body.Append("</blockquote>");
                                } else {
                                    sb_body.Insert(0, Application["sharpwebmail/send/message/replyquotechar"].ToString());
                                    sb_body.Replace("\n", System.String.Concat("\n", Application["sharpwebmail/send/message/replyquotechar"]));
                                }
                            }
                            sb_body.Insert(0, line_end);
                            sb_body.Insert(0, " ");
                            this.FCKEditor.Value = sb_body.ToString();
                        }
                    }
                    details = null;
                }
            } else if ( !this.IsPostBack ) {
                System.String to = Page.Request.QueryString["to"];
                if ( to!=null && to.Length>0 ) {
                    this.toemail.Value = to;
                }
            }
            if ( this.fromname.Value.Length>0 || this.IsPostBack )
                Session["DisplayName"] = this.fromname.Value;
            if ( this.fromname.Value.Length==0 && Session["DisplayName"]!=null )
                this.fromname.Value = Session["DisplayName"].ToString();
            if ( this.fromemail.Value.Length>0 || this.IsPostBack )
                Session["DisplayEmail"] = this.fromemail.Value;
        }
 /// <summary>
 /// 为HtmlInputFile控件设置值
 /// </summary>
 /// <param name="inputFile">HtmlInputFile对象</param>
 private void SetInputFileInfo(System.Web.UI.HtmlControls.HtmlInputFile inputFile)
 {
     this._inputFile = inputFile;
     this._inputFileContentLength = inputFile.PostedFile.ContentLength;
     this._inputFileName = inputFile.PostedFile.FileName;
     this._inputFileValue = inputFile.Value;
 }