コード例 #1
1
ファイル: Uploader.cs プロジェクト: Henr9762/GrenaaKajakklup
        public string UploadFile(HttpPostedFile fileToUpload, string saveToPath, bool randomFileName,
            string allowExtentons)
        {
            string strFileName;
            string strLongFilePath = fileToUpload.FileName;
            bool done = false;
            strFileName = Path.GetFileName(strLongFilePath);


            if (allowExtentons.Length > 1)
            {
                string extentions = allowExtentons.Replace(" ", "").ToLower();
                extentions = allowExtentons.Replace(".", "");
                string[] arrExt = extentions.Split(',');

                foreach (string ext in arrExt)
                {
                    if ("." + ext == Path.GetExtension(strFileName))
                    {
                        if (randomFileName)
                        {
                            strFileName = GenRndName() + Path.GetExtension(strFileName);

                        }
                        else
                        {
                            strFileName = ReplaceChars(strFileName);
                        }

                        fileToUpload.SaveAs(saveToPath + strFileName);

                        done = true;
                    }

                }

            }
            else
            {
                if (randomFileName)
                {
                    strFileName = GenRndName() + Path.GetExtension(strFileName);
                }
                else
                {
                    strFileName = ReplaceChars(strFileName);
                }
                fileToUpload.SaveAs(saveToPath + strFileName);
                done = true;
            }

            if (done)
            {
                return saveToPath + strFileName;
            }
            else
            {
                return null;
            }
        }
コード例 #2
0
    public string SaveFile(HttpPostedFile file)
    {
        if (file == null || file.FileName == "")
            throw new Exception("缺少文件");

        String uploadPath = Server.MapPath(Helper.WeiXinImagePath); //设置保存目录

        String imageName = Guid.NewGuid().ToString(); ; //采用UUID的方式随机命名

        string type = file.FileName.Substring(file.FileName.LastIndexOf("."));

        string path = uploadPath + imageName + type;

        if (file.ContentType.Substring(0, 5) == "image")
        {
            //保存图片
            file.SaveAs(path);

            return imageName + type;
        }
        else
        {
            throw new Exception("文件格式错误");
        }
    }
コード例 #3
0
    public StateInfo FileSaveAs(HttpPostedFile _postedFile, bool _isWater, string ImgType)
    {
        StateInfo info = new StateInfo();
        try
        {
            string str = _postedFile.FileName.Substring(_postedFile.FileName.LastIndexOf(".") + 1);
            if (!this.CheckFileExt(this.wsi.WebFileType, str))
            {
                info.State = 0;
                info.Info = "不允许上传" + str + "类型的文件!";
            }
            if ((this.wsi.WebFileSize > 0) && (_postedFile.ContentLength > (this.wsi.WebFileSize * 0x400)))
            {
                info.State = 0;
                info.Info = "文件超过限制的大小啦!";
            }
            string str2 = DateTime.Now.ToString("yyyyMMddHHmmssff") + "." + str;
            if (!this.wsi.WebFilePath.StartsWith("jquery.easyui/"))
            {
                this.wsi.WebFilePath = "jquery.easyui/" + this.wsi.WebFilePath;
            }
            if (!this.wsi.WebFilePath.EndsWith("/"))
            {
                this.wsi.WebFilePath = this.wsi.WebFilePath + "/";
            }
            string str3 = ImgType + "/";
            this.wsi.WebFilePath = this.wsi.WebFilePath + str3;
            string imgPath = this.wsi.WebFilePath + str2;
            string path = HttpContext.Current.Server.MapPath(this.wsi.WebFilePath);
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            string filename = path + str2;
            _postedFile.SaveAs(filename);
            if (((this.wsi.IsWatermark > 0) && _isWater) && this.CheckFileExt("BMP|JPEG|JPG|GIF|PNG|TIFF", str))
            {
                switch (this.wsi.IsWatermark)
                {
                    case 1:
                        ImageWaterMark.AddImageSignText(imgPath, this.wsi.WebFilePath + str2, this.wsi.WaterText, this.wsi.WatermarkStatus, this.wsi.ImgQuality, this.wsi.WaterFont, this.wsi.FontSize);
                        break;

                    case 2:
                        ImageWaterMark.AddImageSignPic(imgPath, this.wsi.WebFilePath + str2, this.wsi.ImgWaterPath, this.wsi.WatermarkStatus, this.wsi.ImgQuality, this.wsi.ImgWaterTransparency);
                        break;
                }
            }
            info.State = 1;
            info.Info = str3 + str2;
        }
        catch
        {
            info.State = 0;
            info.Info = "传过程中发生意外错误!";
        }
        return info;
    }
コード例 #4
0
        public HttpResponseMessage AddMovie()
        {
            try
            {
                var userName = User.Identity.Name;
                if (!CinemaService.IsAdmin(userName))
                {
                    throw (new UnauthorizedAccessException("The access is only for admins"));
                }

                HttpPostedFile file = HttpContext.Current.Request.Files["img"];
                var            cat  = HttpContext.Current.Request.Params["catagory"].ToString();
                string         ext  = Path.GetExtension(file?.FileName);
                var            guid = Guid.NewGuid();

                int?catagory = null;
                foreach (string c in Enum.GetNames(typeof(Catagory)))
                {
                    if (c == cat)
                    {
                        catagory = (int)Enum.Parse(typeof(Catagory), c);
                        break;
                    }
                }
                if (catagory == null)
                {
                    throw (new FormatException("There is no such catagory"));
                }

                //Need to be changed when we have real server
                var serverPath = @"C:\Users\nissi\OneDrive\מסמכים\GitHub\CinemaWebSite\FinalProject_Cinema\CinemaClient\poster\";

                CinemaService.AddMovie(
                    HttpContext.Current.Request.Params["name"].ToString(),
                    Convert.ToDateTime(HttpContext.Current.Request.Params["movie_date"]),
                    Convert.ToInt32(HttpContext.Current.Request.Params["num_of_seat"]),
                    Convert.ToInt32(HttpContext.Current.Request.Params["ticket_price"]),
                    Convert.ToInt32(HttpContext.Current.Request.Params["p_year"]),
                    Convert.ToInt32(HttpContext.Current.Request.Params["length"]),
                    "../poster/" + guid + ext,
                    catagory.Value);

                file?.SaveAs(serverPath + guid + ext);
                return(Request.CreateResponse(HttpStatusCode.OK, true));
            }
            catch (Exception ex)
            {
                return(Request.CreateResponse(HttpStatusCode.Forbidden, ex.Message));
            }
        }
コード例 #5
0
    /**
  * 上传文件的主处理方法
  * @param HttpContext
  * @param string
  * @param  string[]
  *@param int
  * @return Hashtable
  */
    public  Hashtable upFile(HttpContext cxt, string pathbase, string[] filetype, int size)
    {
        pathbase = pathbase + "/";
        uploadpath = cxt.Server.MapPath(pathbase);//获取文件上传路径

        try
        {
            uploadFile = cxt.Request.Files[0];
            originalName = uploadFile.FileName;

            //目录创建
            createFolder();

            //格式验证
            if (checkType(filetype))
            {
                //不允许的文件类型
                state = "\u4e0d\u5141\u8bb8\u7684\u6587\u4ef6\u7c7b\u578b";
            }
            //大小验证
            if (checkSize(size))
            {
                //文件大小超出网站限制
                state = "\u6587\u4ef6\u5927\u5c0f\u8d85\u51fa\u7f51\u7ad9\u9650\u5236";
            }
            //保存图片
            if (state == "SUCCESS")
            {
                filename = NameFormater.Format(cxt.Request["fileNameFormat"], originalName);
                var testname = filename;
                var ai = 1;
                while (File.Exists(uploadpath + testname))
                {
                    testname =  Path.GetFileNameWithoutExtension(filename) + "_" + ai++ + Path.GetExtension(filename); 
                }
                uploadFile.SaveAs(uploadpath + testname);
                URL = pathbase + testname;
            }
        }
        catch (Exception)
        {
            // 未知错误
            state = "\u672a\u77e5\u9519\u8bef";
            URL = "";
        }
        return getUploadInfo();
    }
コード例 #6
0
    /**
  * 上传文件的主处理方法
  * @param HttpContext
  * @param string
  * @param  string[]
  *@param int
  * @return Hashtable
  */
    public  Hashtable upFile(HttpContext cxt, string pathbase, string[] filetype, int size)
    {
        pathbase = pathbase + DateTime.Now.ToString("yyyy-MM-dd") + "/";
        uploadpath = cxt.Server.MapPath(pathbase);//获取文件上传路径

        try
        {
            uploadFile = cxt.Request.Files[0];
            originalName = uploadFile.FileName;

            //目录创建
            createFolder();

            //格式验证
            if (checkType(filetype))
            {
                //不允许的文件类型
                state = "\u4e0d\u5141\u8bb8\u7684\u6587\u4ef6\u7c7b\u578b";
            }
            //大小验证
            if (checkSize(size))
            {
                //文件大小超出网站限制
                state = "\u6587\u4ef6\u5927\u5c0f\u8d85\u51fa\u7f51\u7ad9\u9650\u5236";
            }
            //保存图片
            if (state == "SUCCESS")
            {
                filename = reName();
                uploadFile.SaveAs(uploadpath + filename);
                URL = pathbase + filename;
            }
        }
        catch (Exception e)
        {
            // 未知错误
            state = "\u672a\u77e5\u9519\u8bef";
            URL = "";
        }
        return getUploadInfo();
    }
コード例 #7
0
ファイル: Uploader.cs プロジェクト: yunxiaokeji/IntFactory
    /**
  * 上传文件的主处理方法
  * @param HttpContext
  * @param string
  * @param  string[]
  *@param int
  * @return Hashtable
  */
    public Hashtable upFile(HttpContext cxt, string pathbase, string[] filetype, int size)
    {
        pathbase = pathbase + DateTime.Now.ToString("yyyy-MM-dd") + "/";
        uploadpath = cxt.Server.MapPath(pathbase);//获取文件上传路径

        try
        {
            uploadFile = cxt.Request.Files[0];
            originalName = uploadFile.FileName;

            //目录创建
            createFolder();

            //格式验证
            if (checkType(filetype))
            {
                state = "不允许的文件类型";
            }
            //大小验证
            if (checkSize(size))
            {
                state = "文件大小超出网站限制";
            }
            //保存图片
            if (state == "SUCCESS")
            {
                filename = reName();
                uploadFile.SaveAs(uploadpath + filename);
                URL = pathbase + filename;
            }
        }
        catch (Exception e)
        {
            state = "未知错误";
            URL = "";
        }
        return getUploadInfo();
    }
コード例 #8
0
ファイル: PictureSave.cs プロジェクト: sorensindgart/Viking
    //public static string SavePicture(FileUpload FU, string GemHer, int Str, string NytFilNavn )
    public static string SavePicture(HttpPostedFile FU, string GemHer, int Str, string NytFilNavn)
    {
        // Eks. GemmesHer går fra eks. /gfx/big til C:\Marianne\asp.net\_CSHARP\Soda-Marianne\gfx/big
        string extension = Path.GetExtension(FU.FileName).ToLower(); //.jpg

        if (extension == ".jpg" || extension == ".jpeg" || extension == ".gif" || extension == ".png")
        {
            try
            {
                String TempImage;
                String NytImage;

                // TEMPIMAGE - arbejdsfilen - prefikses med _temp_, gemmes i mappen hvor det færdige billede skal gemmes, og bliver gjort til streamin for nye billede
                TempImage = Path.Combine(HttpContext.Current.Request.PhysicalApplicationPath, GemHer) + "_temp_" + NytFilNavn;
                FU.SaveAs(TempImage);
                StreamReader StreamIn = new StreamReader(TempImage);
                // NYTIMAGE - måske flere placeringer - måske flere størrelser
                NytImage = Path.Combine(HttpContext.Current.Request.PhysicalApplicationPath, GemHer) + NytFilNavn;
                StreamWriter StreamOut = new StreamWriter(NytImage);
                imageResize.ResizeImage(Str, StreamIn.BaseStream, StreamOut.BaseStream);
                // LUK streams og slet TEMP-billede
                StreamOut.Close();
                StreamIn.Close();
                IOFunctions.DeleteFile(TempImage);
            }
            catch (Exception)
            {
                throw;
            }
        }
        else
        {
            NytFilNavn = "test.jpg";
        }
        return NytFilNavn;
    }
コード例 #9
0
ファイル: Uploader.cs プロジェクト: cnbin/HLB
    /**
      * �ϴ��ļ������������
      * @param HttpContext
      * @param string
      * @param  string[]
      *@param int
      * @return Hashtable
      */
    public Hashtable upFile(HttpContext cxt, string pathbase, string[] filetype, int size)
    {
        pathbase = pathbase + DateTime.Now.ToString("yyyy-MM-dd") + "/";
        uploadpath = cxt.Server.MapPath(pathbase);//��ȡ�ļ��ϴ�·��

        try
        {
            uploadFile = cxt.Request.Files[0];
            originalName = uploadFile.FileName;

            //Ŀ¼����
            createFolder();

            //��ʽ��֤
            if (checkType(filetype))
            {
                state = "��������ļ�����";
            }
            //��С��֤
            if (checkSize(size))
            {
                state = "�ļ���С������վ����";
            }
            //����ͼƬ
            if (state == "SUCCESS")
            {
                filename = reName();
                uploadFile.SaveAs(uploadpath + filename);
                URL = pathbase + filename;
            }
        }
        catch (Exception e)
        {
            state = "δ֪����"+e.Message;
            URL = "";
        }
        return getUploadInfo();
    }
コード例 #10
0
ファイル: UpLoad.aspx.cs プロジェクト: xxgkgk/UnifyNet
 /// <summary>
 /// 单独文件上载处理
 /// </summary>
 /// <param name="HPF">上载文件对象</param>
 /// <param name="FileType">允许的类型(gif,jpg,txt...)</param>
 /// <param name="FileSize">允许的大小(KB)</param>
 /// <param name="FilePath">保存的路径(相对路径)</param>
 /// <returns>List[0]=类型是否允许,List[1]=大小是否允许,List[2]=保存的文件名称</returns>
 public List<string> GetUpLoad(HttpPostedFile HPF, string[] FileType, int FileSize, string FilePath)
 {
     List<string> _List = new List<string>();
     string _ContentType = HPF.ContentType;
     string _IsType = "false";
     //文件类型判断
     for (int i = 0; i < FileType.Length; i++)
     {
         List<string> _ListMIME = GetMIME(FileType[i]);
         for (int n = 0; n < _ListMIME.Count; n++)
         {
             if (_ListMIME[n] == _ContentType)
             {
                 _IsType = "true";
                 break;
             }
         }
         if (_IsType == "true")
         {
             break;
         }
     }
     //文件大小判断
     string _IsSize = "false";
     if (HPF.ContentLength <= FileSize * 1024)
     {
         _IsSize = "true";
     }
     string _UpFileUrl = "";
     string _UpFileName = "";
     if (_IsType == "true" && _IsSize == "true")
     {
         //获得文件扩展名
         string _FileExt = System.IO.Path.GetExtension(HPF.FileName).ToLower();
         //产生随机文件名
         _UpFileName = DateTime.Now.ToString("yyyyMMddHHmmss") + "-" + new Random().Next(1, 9999) + _FileExt;
         _UpFileUrl = FilePath + "/" + _UpFileName;
         //创建文件夹
         DirectoryInfo _DirectoryInfo = new DirectoryInfo(System.Web.HttpContext.Current.Server.MapPath(FilePath));
         if (_DirectoryInfo.Exists == false)
         {
             _DirectoryInfo.Create();
         }
         //保存文件
         HPF.SaveAs(System.Web.HttpContext.Current.Server.MapPath(_UpFileUrl));
     }
     _List.Add(_IsType);
     _List.Add(_IsSize);
     _List.Add(_UpFileName);
     return _List;
 }
コード例 #11
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (base.Request.QueryString["delimg"] != null)
            {
                string str = base.Server.HtmlEncode(base.Request.QueryString["delimg"]);
                str = base.Server.MapPath(str);
                if (File.Exists(str))
                {
                    File.Delete(str);
                }
                base.Response.Write("0");
                base.Response.End();
            }
            Image        image        = null;
            Image        image1       = null;
            Bitmap       bitmap       = null;
            Graphics     graphic      = null;
            MemoryStream memoryStream = null;
            int          num          = int.Parse(base.Request.QueryString["imgurl"]);

            try
            {
                try
                {
                    if (num >= 1)
                    {
                        base.Response.Write("0");
                    }
                    else
                    {
                        HttpPostedFile item = base.Request.Files["Filedata"];
                        DateTime       now  = DateTime.Now;
                        string         str1 = now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo);
                        string         str2 = "/Storage/data/DistributorLogoPic/";
                        string         str3 = string.Concat(str1, Path.GetExtension(item.FileName));
                        item.SaveAs(Globals.MapPath(string.Concat(str2, str3)));
                        base.Response.StatusCode = 200;
                        base.Response.Write(string.Concat(str1, "|/Storage/data/DistributorLogoPic/", str3));
                    }
                }
                catch                // (Exception exception)
                {
                    base.Response.StatusCode = 500;
                    base.Response.Write("服务器错误");
                    base.Response.End();
                }
            }
            finally
            {
                if (bitmap != null)
                {
                    bitmap.Dispose();
                }
                if (graphic != null)
                {
                    graphic.Dispose();
                }
                if (image1 != null)
                {
                    image1.Dispose();
                }
                if (image != null)
                {
                    image.Dispose();
                }
                if (memoryStream != null)
                {
                    memoryStream.Close();
                }
                base.Response.End();
            }
        }
コード例 #12
0
ファイル: Util.cs プロジェクト: lakeli/shizong
 /// <summary>
 /// LargeIMGPath原图路径,IMGPath缩略图路径,pathIndex指定路径前缀,pathMid指定路径嵌入字符以区分原图或缩略图
 /// </summary>
 /// <param name="LargeIMGPath"></param>
 /// <param name="IMGPath"></param>
 /// <param name="Server"></param>
 /// <param name="fu"></param>
 /// <param name="pathIndex"></param>
 /// <param name="pathMid"></param>
 public static void uploadIMG(ref string LargeIMGPath, ref string IMGPath, HttpServerUtility Server, HttpPostedFile PostedFile, string FileName, string pathIndex, string pathMid)
 {
     try
     {
         string CurrentDatatime = Convert.ToString(System.DateTime.Now.Year.ToString() + System.DateTime.Now.Month.ToString() + System.DateTime.Now.Day.ToString() + System.DateTime.Now.Minute.ToString() + System.DateTime.Now.Second.ToString() + System.DateTime.Now.Millisecond.ToString());
         //保存原图
         LargeIMGPath = pathIndex + CurrentDatatime + pathMid + FileName.ToString();
         LargeIMGPath = LargeIMGPath.Replace("%", "");
         string Large_IMG_FullName = Server.MapPath(pathIndex) + CurrentDatatime + pathMid + FileName.ToString();
         Large_IMG_FullName = Large_IMG_FullName.Replace("%", "");
         PostedFile.SaveAs(Large_IMG_FullName);
         //生成缩略图并保存
         IMGPath = pathIndex + CurrentDatatime + FileName.ToString();
         IMGPath=IMGPath.Replace("%", "");
         string IMG_FullName = Server.MapPath(pathIndex) + CurrentDatatime + FileName.ToString();
         IMG_FullName = IMG_FullName.Replace("%", "");
         Thumbnail.MakeThumbnail(Large_IMG_FullName, IMG_FullName, 300, 300, Enums.ImageThumbnail.HWC);
     }
     catch
     {
         throw new Exception("上传文件失败!");
     }
 }
コード例 #13
0
    protected void btnSalvar_Click(object sender, EventArgs e)
    {
        Empresas id  = (Empresas)Session["emp_empresa"];
        Empresas emp = new Empresas();
        Imagens  img = new Imagens();



        if (EscolheCategoria.SelectedValue == "1")
        {
            Produtos pro = new Produtos();
            pro.Pro_nome           = ProNome.Text;
            pro.Pro_tipo           = ProTipo.Text;
            pro.Pro_descricao      = ProDesc.Text;
            pro.Pro_caracteristica = ProCarac.Text;
            pro.Pro_quantidade     = Convert.ToInt32(ProQtd.Text);
            pro.Pro_vencimento     = Convert.ToDateTime(ProVenc.Text);
            pro.Pro_valor          = Convert.ToDouble(ProValor.Text);

            //FK
            emp.Emp_id = Convert.ToInt32(id.Emp_id);
            pro.Emp_id = emp;
            pro.Pro_id = ProdutosDB.Insert(pro);


            img.Pro_id = pro;
            if (FileUploadControl.PostedFile.ContentLength < 8388608)
            {
                try
                {
                    if (FileUploadControl.HasFile)
                    {
                        try
                        {
                            //Aqui ele vai filtrar pelo tipo de arquivo
                            if (FileUploadControl.PostedFile.ContentType == "image/jpeg" ||
                                FileUploadControl.PostedFile.ContentType == "image/png" ||
                                FileUploadControl.PostedFile.ContentType == "image/gif" ||
                                FileUploadControl.PostedFile.ContentType == "image/bmp")
                            {
                                try
                                {
                                    //Obtem o  HttpFileCollection
                                    HttpFileCollection hfc = Request.Files;
                                    for (int i = 0; i < hfc.Count; i++)
                                    {
                                        HttpPostedFile hpf = hfc[i];
                                        if (hpf.ContentLength > 0)
                                        {
                                            //Pega o nome do arquivo
                                            string nome = System.IO.Path.GetFileName(hpf.FileName);
                                            //Pega a extensão do arquivo
                                            string extensao = Path.GetExtension(hpf.FileName);
                                            //Gera nome novo do Arquivo numericamente
                                            string filename = string.Format("{0:00000000000000}", GerarID());
                                            //Caminho a onde será salvo
                                            hpf.SaveAs(Server.MapPath("~/FotoProduto/") + filename + i
                                                       + extensao);

                                            //Prefixo p/ img m
                                            var prefixoG = "-m";

                                            //pega o arquivo já carregado
                                            string pth = Server.MapPath("~/FotoProduto/")
                                                         + filename + i + extensao;

                                            //Redefine altura e largura da imagem e Salva o arquivo + prefixo
                                            Redefinir.resizeImageAndSave(pth, 500, 331, prefixoG);
                                            //     H    V

                                            img.Img_url = "../FotoProduto/" + filename + i + prefixoG + extensao;

                                            File.Delete(Request.PhysicalApplicationPath + "FotoProduto\\" + filename + i + extensao);

                                            switch (ImagensDB.InsertImgProduto(img))
                                            {
                                            case -2:
                                                ltl.Text = "<p class='text-success'>Erro no produto</p>";
                                                Page.ClientScript.RegisterStartupScript(this.GetType(), "script", "<script>$('#myModal').modal('show');</script>", false);
                                                break;

                                            default:
                                                ltl.Text = "<p class='text-success'>Produto adicionado com sucesso</p>";
                                                Page.ClientScript.RegisterStartupScript(this.GetType(), "script", "<script>$('#myModal').modal('show');</script>", false);
                                                LimpaCampos();
                                                break;
                                            }
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    throw;
                                }
                                // Mensagem se tudo ocorreu bem
                                StatusLabel.Text = "Todas imagens carregadas com sucesso!";
                            }
                            else
                            {
                                // Mensagem notifica que é permitido carregar apenas
                                // as imagens definida la em cima.
                                StatusLabel.Text = "É permitido carregar apenas imagens!";
                            }
                        }
                        catch (Exception ex)
                        {
                            // Mensagem notifica quando ocorre erros
                            StatusLabel.Text = "O arquivo não pôde ser carregado. O seguinte erro ocorreu: " + ex.Message;
                        }
                    }
                }
                catch (Exception ex)
                {
                    // Mensagem notifica quando ocorre erros
                    StatusLabel.Text = "O arquivo não pôde ser carregado. O seguinte erro ocorreu: " + ex.Message;
                }
            }
            else
            {
                // Mensagem notifica quando imagem é superior a 8 MB
                StatusLabel.Text = "Não é permitido carregar mais do que 8 MB";
            }
        }
        else
        {
            Servicos ser = new Servicos();
            ser.Ser_nome           = ServNome.Text;
            ser.Ser_descricao      = ServDesc.Text;
            ser.Ser_caracteristica = ServCarac.Text;
            ser.Ser_valor          = Convert.ToInt32(ServValor.Text);

            //FK
            emp.Emp_id = Convert.ToInt32(id.Emp_id);
            ser.Emp_id = emp;
            ser.Ser_id = ServicosDB.Insert(ser);

            img.Ser_id = ser;



            if (FileUploadControl.PostedFile.ContentLength < 8388608)
            {
                try
                {
                    if (FileUploadControl.HasFile)
                    {
                        try
                        {
                            //Aqui ele vai filtrar pelo tipo de arquivo
                            if (FileUploadControl.PostedFile.ContentType == "image/jpeg" ||
                                FileUploadControl.PostedFile.ContentType == "image/png" ||
                                FileUploadControl.PostedFile.ContentType == "image/gif" ||
                                FileUploadControl.PostedFile.ContentType == "image/bmp")
                            {
                                try
                                {
                                    //Obtem o  HttpFileCollection
                                    HttpFileCollection hfc = Request.Files;
                                    for (int i = 0; i < hfc.Count; i++)
                                    {
                                        HttpPostedFile hpf = hfc[i];
                                        if (hpf.ContentLength > 0)
                                        {
                                            //Pega o nome do arquivo
                                            string nome = System.IO.Path.GetFileName(hpf.FileName);
                                            //Pega a extensão do arquivo
                                            string extensao = Path.GetExtension(hpf.FileName);
                                            //Gera nome novo do Arquivo numericamente
                                            string filename = string.Format("{0:00000000000000}", GerarID());
                                            //Caminho a onde será salvo
                                            hpf.SaveAs(Server.MapPath("~/FotoProduto/") + filename + i
                                                       + extensao);

                                            //Prefixo p/ img m
                                            var prefixoG = "-m";

                                            //pega o arquivo já carregado
                                            string pth = Server.MapPath("~/FotoProduto/")
                                                         + filename + i + extensao;

                                            //Redefine altura e largura da imagem e Salva o arquivo + prefixo
                                            Redefinir.resizeImageAndSave(pth, 500, 331, prefixoG);
                                            //     H    V

                                            img.Img_url = "../FotoProduto/" + filename + i + prefixoG + extensao;

                                            File.Delete(Request.PhysicalApplicationPath + "FotoProduto\\" + filename + i + extensao);

                                            switch (ImagensDB.InsertImgServico(img))
                                            {
                                            case -2:
                                                ltl.Text = "<p class='text-success'>Erro no serviço</p>";
                                                Page.ClientScript.RegisterStartupScript(this.GetType(), "script", "<script>$('#myModal').modal('show');</script>", false);
                                                break;

                                            default:
                                                ltl.Text = "<p class='text-success'>Serviço adicionado com sucesso</p>";
                                                Page.ClientScript.RegisterStartupScript(this.GetType(), "script", "<script>$('#myModal').modal('show');</script>", false);
                                                LimpaCampos();
                                                break;
                                            }
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    throw;
                                }
                                // Mensagem se tudo ocorreu bem
                                StatusLabel.Text = "Todas imagens carregadas com sucesso!";
                            }
                            else
                            {
                                // Mensagem notifica que é permitido carregar apenas
                                // as imagens definida la em cima.
                                StatusLabel.Text = "É permitido carregar apenas imagens!";
                            }
                        }
                        catch (Exception ex)
                        {
                            // Mensagem notifica quando ocorre erros
                            StatusLabel.Text = "O arquivo não pôde ser carregado. O seguinte erro ocorreu: " + ex.Message;
                        }
                    }
                }
                catch (Exception ex)
                {
                    // Mensagem notifica quando ocorre erros
                    StatusLabel.Text = "O arquivo não pôde ser carregado. O seguinte erro ocorreu: " + ex.Message;
                }
            }
            else
            {
                // Mensagem notifica quando imagem é superior a 8 MB
                StatusLabel.Text = "Não é permitido carregar mais do que 8 MB";
            }
        }
    }
コード例 #14
0
ファイル: Add.aspx.cs プロジェクト: cawed-never/final
        protected void Upload_Click(object sender, EventArgs e)
        {
            if (FileUpload1.HasFile)
            {
                try
                {
                    SqlConnection cn = new SqlConnection();
                    // 連接字串指定連接資料庫
                    cn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["NewsConnection"].ConnectionString;
                    cn.Open();  // 連接資料庫


                    HttpPostedFile postedFile = this.FileUpload1.PostedFile;
                    String         fileName   = "";
                    String         filePath   = "~/File/" + Number.Text + "/";
                    fileName = Path.GetFileName(postedFile.FileName);

                    if (Directory.Exists(Server.MapPath(filePath)) == false)
                    {
                        Directory.CreateDirectory(Server.MapPath(filePath));
                    }
                    else
                    {
                        if (string.IsNullOrEmpty(year.Text) || string.IsNullOrEmpty(Sday.Text) || string.IsNullOrEmpty(Sday.Text) ||
                            string.IsNullOrEmpty(Eday.Text) || string.IsNullOrEmpty(Local.Text) || string.IsNullOrEmpty(Content.Text) ||
                            string.IsNullOrEmpty(Time.Text))
                        {
                            Page.ClientScript.RegisterStartupScript(this.GetType(), "message", "alert('每個欄位都必須填寫')", true);
                        }
                        else
                        {
                            Double   n;
                            int      m;
                            DateTime st = Convert.ToDateTime(Sday.Text);
                            DateTime et = Convert.ToDateTime(Eday.Text);
                            if (!int.TryParse(year.Text, out m))
                            {
                                Page.ClientScript.RegisterStartupScript(this.GetType(), "message", "alert('登錄學年必須為數字')", true);
                            }
                            else if (!Double.TryParse(Time.Text, out n))
                            {
                                Page.ClientScript.RegisterStartupScript(this.GetType(), "message", "alert('服務時數必須為數字')", true);
                            }
                            else if (st >= et)
                            {
                                Page.ClientScript.RegisterStartupScript(this.GetType(), "message", "alert('開始日期不能大於結束日期')", true);
                            }
                            else
                            {
                                if (fileName != "")
                                {
                                    String fileType = Path.GetExtension(fileName);
                                    postedFile.SaveAs(MapPath(filePath + fileName));
                                    string finalFilePath = MapPath(filePath + fileName);

                                    string sqlstr = "INSERT INTO [服務時數填寫] ([學號],[姓名],[登入服務活動的年期(EX:1072)],[服務類別]," +
                                                    "[開始日期],[結束日期],[服務單位],[服務內容],[主辦(EX:校內/校外/社團)],[服務時數],[電子證明文件]) VALUES " +
                                                    "('" + Number.Text + "',N'" + Name.Text + "','" + year.Text + "',N'" +
                                                    DropDownList1.SelectedValue + "','" + Sday.Text + "','" + Eday.Text + "',N'" +
                                                    Local.Text + "',N'" + Content.Text + "',N'" + Zone.Text + "','" + Time.Text + "',N'" + finalFilePath + "')";

                                    //建立SqlCommand物件cmd
                                    SqlCommand cmd = new SqlCommand(sqlstr, cn);

                                    cmd.ExecuteNonQuery();
                                    SystemMes.Text = "新增資料成功!";
                                    Upload.Visible = false;
                                    Next.Visible   = true;
                                }
                                else
                                {
                                    Page.ClientScript.RegisterStartupScript(this.GetType(), "message", "alert('請選擇檔案')", true);
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    UploadMes.Text = "發生錯誤:" + ex.Message.ToString();
                }
            }
            else
            {
                UploadMes.Text = "沒有選擇要上傳的檔案!";
            }
        }
コード例 #15
0
        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                string LogoImageName = string.Empty;
                byte[] LogoImage     = null;
                if (UpdLogo.PostedFile != null && UpdLogo.PostedFile.FileName != "")
                {
                    //System.Drawing.Image img = System.Drawing.Image.FromStream(UpdLogo.PostedFile.InputStream);
                    //int height = img.Height;
                    //int width = img.Width;
                    //decimal size = Math.Round(((decimal)UpdLogo.PostedFile.ContentLength / (decimal)1024), 2);
                    //if (height != 96 || width != 271)
                    //{
                    LogoImageName = Path.GetFileName(UpdLogo.FileName);
                    LogoImage     = new byte[UpdLogo.PostedFile.ContentLength];
                    //LogoImage = CreateThumbnail(LogoImage, 420, 98, false);
                    HttpPostedFile UploadedImage = UpdLogo.PostedFile;
                    UploadedImage.InputStream.Read(LogoImage, 0, (int)UpdLogo.PostedFile.ContentLength);
                }
                else
                {
                    //lbllogo.Text = "File size must not exceed 732.27KB";

                    LogoImage = (byte[])ViewState["LogoImage"];
                }
                string FaviconImageName = string.Empty;
                byte[] FaviconImage     = null;
                if (UpdFavicon.PostedFile != null && UpdFavicon.PostedFile.FileName != "")
                {
                    FaviconImageName = Path.GetFileName(UpdFavicon.FileName);
                    FaviconImage     = new byte[UpdFavicon.PostedFile.ContentLength];
                    //FaviconImage = CreateThumbnail(FaviconImage, 420, 98, false);

                    HttpPostedFile UploadedImage = UpdFavicon.PostedFile;
                    UploadedImage.InputStream.Read(FaviconImage, 0, (int)UpdFavicon.PostedFile.ContentLength);
                }
                else
                {
                    FaviconImage = (byte[])ViewState["FaviconImage"];
                }
                //string BannerImageName = string.Empty;
                //byte[] BannerImage = null;
                //if (updbanner.PostedFile != null && updbanner.PostedFile.FileName != "")
                //{
                //    //System.Drawing.Image img = System.Drawing.Image.FromStream(updbanner.PostedFile.InputStream);
                //    //int height = img.Height;
                //    //int width = img.Width;
                //    //decimal size = Math.Round(((decimal)updbanner.PostedFile.ContentLength / (decimal)1024), 2);
                //    //if (width == 420 && height == 98)
                //    //{

                //        BannerImageName = Path.GetFileName(updbanner.FileName);
                //        BannerImage = new byte[updbanner.PostedFile.ContentLength];
                //        //BannerImage = CreateThumbnail(BannerImage, 420, 98, false);

                //        HttpPostedFile UploadedImage = updbanner.PostedFile;
                //        UploadedImage.InputStream.Read(BannerImage, 0, (int)updbanner.PostedFile.ContentLength);
                //    }
                //    else
                //    {
                //        lblheaderlogo.Text = "File size must not exceed 732.27KB";
                //        BannerImage = (byte[])ViewState["LogoImage"];
                //    }

                HttpFileCollection FileColl = Request.Files;

                for (int i = 0; i < FileColl.Count; i++)
                {
                    HttpPostedFile PostedFile = FileColl[i];
                    if (PostedFile.ContentType == "image/jpg" || PostedFile.ContentType == "image/png" || PostedFile.ContentType == "image/bmp")
                    {
                        //you can check image size here
                    }
                    //System.Drawing.Image myImage = System.Drawing.Image.FromStream(PostedFile.InputStream);
                    //if (myImage.Height > 600 && myImage.Width > 1000)//you can check image file size if required
                    //{
                    if (PostedFile.ContentLength > 0)
                    {
                        PostedFile.SaveAs(Server.MapPath("UploadFiles") + "\\" + System.IO.Path.GetFileName(PostedFile.FileName));
                        //Label1.Text = "Saved Successfully";
                    }
                    SqlCommand cmd = new SqlCommand();
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandText = "ups_EditSiteSettings";
                    cmd.Connection  = conn;
                    cmd.Parameters.AddWithValue("@Title", txtTitle.Text);
                    cmd.Parameters.AddWithValue("@Description", txtDescription.Text);
                    cmd.Parameters.AddWithValue("@Keywords", txtKeywords.Text);
                    cmd.Parameters.AddWithValue("@Copyright", txtCopyright.Text);
                    cmd.Parameters.AddWithValue("@UploadLogo", LogoImage);
                    cmd.Parameters.AddWithValue("@Faviconico", FaviconImage);
                    cmd.Parameters.AddWithValue("@SiteTemplate", txtSiteTemplate.Text);
                    cmd.Parameters.AddWithValue("@BannerSettings", txtBanner.Text);
                    cmd.Parameters.AddWithValue("@PhoneNumber", txtphone.Text);
                    cmd.Parameters.AddWithValue("@Mobile", txtmobile.Text);
                    cmd.Parameters.AddWithValue("@Email", txtemail.Text);
                    cmd.Parameters.AddWithValue("@Fax", txtfax.Text);
                    cmd.Parameters.AddWithValue("@ListBrokerage", ddlbrokerage.SelectedItem.Text);


                    if (conn.State == ConnectionState.Closed)
                    {
                        conn.Open();
                    }
                    cmd.ExecuteNonQuery();
                    conn.Close();
                    Response.Redirect("~/Admin/SiteSettings.aspx", false);
                }
            }

            catch (Exception ex)
            {
                //throw ex;
            }
        }
コード例 #16
0
ファイル: fileupload.ashx.cs プロジェクト: nauman22/jqueryasp
        public void ProcessRequest(HttpContext context)
        {
            //D:\jquery1\jquery1\MediaUploader
            const string basePath = @"\\D:\jquery1\jquery1\MediaUploader\";
            const string baseUrl  = @"/jquery1/jquery1/";

            context.Response.ContentType = "text/plain";
            // context.Response.Write("Hello World");
            try
            {
                string   dirFullPath = HttpContext.Current.Server.MapPath("~/MediaUploader/");
                string[] files;
                int      numFiles;
                files    = System.IO.Directory.GetFiles(dirFullPath);
                numFiles = files.Length;
                numFiles = numFiles + 1;
                string   str_image       = "";
                string   pathToSave_100  = "";
                string   CKEditorFuncNum = ""; //= context.Request["CKEditorFuncNum"];
                string   fileName        = "";
                string   json            = "";
                string   mynewfilename   = "";
                Int64    datetimeticks   = DateTime.Now.Ticks;
                DateTime formatdate      = new DateTime(datetimeticks);
                System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();

                foreach (string s in context.Request.Files)
                {
                    HttpPostedFile file = context.Request.Files[s];

                    fileName = file.FileName;
                    string validTestName = fileName.Remove(0, fileName.Length);
                    // string validImagedate = imageData.Remove(0, 22);
                    validTestName = validTestName.Replace(" ", "_");
                    string extension     = System.IO.Path.GetExtension(fileName).Remove(0, 1).ToLower();
                    string fileExtension = file.ContentType;
                    CKEditorFuncNum = context.Request["CKEditorFuncNum"];
                    //  string[] filetypes = { "application/pdf", "image/jpeg", "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "text/plain", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "application/vnd.ms-excel" };
                    string[] filetypes = { "image/jpeg", "image/jpg", "image/png", "image/gif", "image/bmp" };
                    if (!string.IsNullOrEmpty(fileName))
                    {
                        //string extension = System.IO.Path.GetExtension(filename).Remove(0, 1).ToLower();
                        if (context.Request.Files[0].InputStream.Length > 1048576)
                        {
                            //  string msg = GetResource("Upload_Error_1", culture, "File exceeds maximum size allowed ({0} Mb)");
                            // customer = new { uploaded = "1", fileName = fileName, url = str_image };
                            var customer = new { uploaded = "0", fileName = fileName, url = str_image, error = "This file can't be uploaded due to exceed the maximum size limit (2 MB)" };
                            json = serializer.Serialize(customer);
                        }
                        else if (!filetypes.Contains(file.ContentType))
                        {
                            var customer = new { uploaded = "0", fileName = fileName, url = str_image, error = "This file can't be uploaded. Only Image file allowed." };
                            json = serializer.Serialize(customer);
                        }
                        else
                        {
                            fileExtension = Path.GetExtension(fileName);

                            mynewfilename = validTestName + formatdate.ToString("dd-M-yyyy-HH-mm-ss") + fileExtension;
                            //  str_image = "MyPHOTO_" + numFiles.ToString() + fileExtension;
                            pathToSave_100 = HttpContext.Current.Server.MapPath("~/MediaUploader/") + mynewfilename;
                            //   Server.MapPath("~/Uploads/User_" + userId + "/");
                            str_image = "http:/MediaUploader/" + mynewfilename;
                            // path = string.Format("{0}/{1}", HttpContext.Current.Server.MapPath("~/MediaUploader/"), fileName);
                            file.SaveAs(pathToSave_100);

                            var customer = new { uploaded = "1", fileName = mynewfilename, url = str_image };
                            json = serializer.Serialize(customer);
                        }
                    }
                }
                //  database record update logic here  ()
                //string url = basePath + fileName;
                //context.Response.Write("<script>window.parent.CKEDITOR.tools.callFunction(" + CKEditorFuncNum + ", \"" + url + "\");</script>");
                //context.Response.End();

                //var customer = new { uploaded = "1", fileName = fileName, url = str_image };
                //string json = serializer.Serialize(customer);

                //context.Response.ContentType = "application/json";
                // context.Response.Charset = "UTF-8";
                context.Response.Write(json);
                // context.Response.Write(str_image);
                context.Response.End();
                // return (pathToSave_100);
            }
            catch (Exception ac)
            {
            }
        }
コード例 #17
0
        protected void btnDangBai_Click(object sender, EventArgs e)
        {
            HttpFileCollection _HttpFileCollection = Request.Files;
            HttpPostedFile     HttpPostedFile      = _HttpFileCollection[0];
            int           MaKH = int.Parse(Session["MaKH"].ToString());
            DateTime      NgayDang = DateTime.Now, NgayHetHan = NgayDang.AddDays(int.Parse(txtSoNgay.Text));
            SqlConnection con = new SqlConnection(XLDL.strCon);

            con.Open();
            SqlCommand cmd = new SqlCommand();

            cmd.CommandType = CommandType.Text;
            cmd.Connection  = con;
            cmd.CommandText = @"Insert into NhaTroChoThue(MaKH,TinhThanh,QuanHuyen,PhuongXa,TenDuong,SoNha,DiaChi,LoaiNT,SDTNguoiChoThue,MoTa,GiaChoThue,DienTich,HinhAnh,NgayDang,NgayHetHan,TieuDe)
                                values(@MaKH,@TinhThanh,@QuanHuyen,@PhuongXa,@TenDuong,@SoNha,@DiaChi,@LoaiNT,@SDTNguoiChoThue,@MoTa,@GiaChoThue,@DienTich,@HinhAnh,@NgayDang,@NgayHetHan,@TieuDe)";
            cmd.Parameters.Add("@MaKH", SqlDbType.Int);
            cmd.Parameters["@MaKH"].Value = MaKH;
            cmd.Parameters.Add("@TinhThanh", SqlDbType.NVarChar, 25);
            cmd.Parameters["@TinhThanh"].Value = drpTinhThanh.SelectedItem.Text;
            cmd.Parameters.Add("@QuanHuyen", SqlDbType.NVarChar, 25);
            cmd.Parameters["@QuanHuyen"].Value = drpQuanHuyen.SelectedItem.Text;
            cmd.Parameters.Add("@PhuongXa", SqlDbType.NVarChar, 50);
            cmd.Parameters["@PhuongXa"].Value = drpPhuongXa.SelectedItem.Text;
            cmd.Parameters.Add("@TenDuong", SqlDbType.NVarChar, 25);
            cmd.Parameters["@TenDuong"].Value = txtDuong.Text;
            cmd.Parameters.Add("@SoNha", SqlDbType.NVarChar, 50);
            cmd.Parameters["@SoNha"].Value = txtSoNha.Text;
            cmd.Parameters.Add("@DiaChi", SqlDbType.NVarChar, 100);
            cmd.Parameters["@DiaChi"].Value = txtDiaChiChinhXac.Text;;
            cmd.Parameters.Add("@LoaiNT", SqlDbType.NVarChar, 30);
            cmd.Parameters["@LoaiNT"].Value = drpLoaiNT.SelectedItem.Text;
            cmd.Parameters.Add("@SDTNguoiChoThue", SqlDbType.NVarChar, 12);
            cmd.Parameters["@SDTNguoiChoThue"].Value = txtThongTinLienHe.Text;
            cmd.Parameters.Add("@MoTa", SqlDbType.NText);
            cmd.Parameters["@MoTa"].Value = txtMoTa.Text;
            cmd.Parameters.Add("@GiaChoThue", SqlDbType.Int);
            cmd.Parameters["@GiaChoThue"].Value = int.Parse(txtGiaChoThue.Text);
            cmd.Parameters.Add("@DienTich", SqlDbType.Int);
            cmd.Parameters["@DienTich"].Value = int.Parse(txtDienTich.Text);
            cmd.Parameters.Add("@HinhAnh", SqlDbType.NVarChar, 50);
            cmd.Parameters["@HinhAnh"].Value = HttpPostedFile.FileName.ToString();
            cmd.Parameters.Add("@NgayDang", SqlDbType.SmallDateTime);
            cmd.Parameters["@NgayDang"].Value = NgayDang;
            cmd.Parameters.Add("@NgayHetHan", SqlDbType.SmallDateTime);
            cmd.Parameters["@NgayHetHan"].Value = NgayHetHan;
            cmd.Parameters.Add("@TieuDe", SqlDbType.NVarChar, 100);
            cmd.Parameters["@TieuDe"].Value = txtTieuDe.Text;
            cmd.ExecuteNonQuery();
            con.Close();
            DataTable     dt   = XLDL.GetData("select max(MaNhaTro) from NhaTroChoThue ");
            int           MaNT = int.Parse(dt.Rows[0][0].ToString());
            SqlConnection con1 = new SqlConnection(XLDL.strCon);

            con1.Open();
            SqlCommand cmd1 = new SqlCommand();

            cmd1.CommandType = CommandType.Text;
            cmd1.Connection  = con1;
            cmd1.CommandText = @"Insert into HinhAnhChiTietNhaTro(MaNhaTro,HinhAnh) values(@MaNT,@HinhAnh) ";
            cmd1.Parameters.Add("@MaNT", SqlDbType.Int);
            cmd1.Parameters["@MaNT"].Value = MaNT;
            cmd1.Parameters.Add("@HinhAnh", SqlDbType.NVarChar, 50);
            for (int i = 0; i < _HttpFileCollection.Count; i++)
            {
                HttpPostedFile _HttpPostedFile = _HttpFileCollection[i];
                if (_HttpPostedFile.ContentLength > 0)
                {
                    string filepath = MapPath("Images/" + Path.GetFileName(_HttpPostedFile.FileName));
                    _HttpPostedFile.SaveAs(filepath);
                    cmd1.Parameters["@HinhAnh"].Value = _HttpPostedFile.FileName.ToString();
                    cmd1.ExecuteNonQuery();
                }
            }
            con1.Close();
            Response.Redirect("~/CamOn.aspx");
        }
コード例 #18
0
    protected void Button1_Click(object sender, EventArgs e)
    {
        FYPDataContext db = new FYPDataContext();


        var ID = (from a in db.LawnOwners
                  where a.Address.Equals(Session["Address"].ToString())
                  select a).FirstOrDefault();

        Session["VVID"] = Convert.ToInt32(ID.Id);
        HttpFileCollection imagecollection = Request.Files;

        if (FileUpload1.HasFiles)
        {
            for (int i = 0; i < imagecollection.Count; i++)
            {
                String         path      = "";
                Image          upload    = new Image();
                HttpPostedFile uploadIma = imagecollection[i];
                string         Extension = System.IO.Path.GetExtension(uploadIma.FileName);
                if (Extension.ToLower() != ".png" && Extension.ToLower() != ".gif" && Extension.ToLower() != ".jpg" && Extension.ToLower() != ".jpeg")
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert('Invalid Image Format');", true);
                }
                else
                {
                    int File = uploadIma.ContentLength;
                    if (File > 1048576)
                    {
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert('Maximam File size is 1 MB');", true);
                    }

                    else
                    {
                        path = "uploadimages/" + Path.GetFileName("" + uploadIma.FileName);

                        if (i == 0)
                        {
                            upload.Name = "Cover";
                        }
                        else
                        {
                            upload.Name = ID.LawnName.ToString();
                        }


                        upload.Uimg   = path;
                        upload.LawnID = Convert.ToInt32(ID.Id);
                        db.Images.InsertOnSubmit(upload);
                        db.SubmitChanges();
                        uploadIma.SaveAs(Server.MapPath("~/uploadimages/" + uploadIma.FileName));
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert('File Uploaded Sucessfully!! :)');", true);
                        PicSuccess.Visible = true;
                    }
                }
            }

            Response.Redirect("VenderHome.aspx");
        }

        else
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert('Please Select Image First');", true);
        }
    }
コード例 #19
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!CmsContext.currentUserCanWriteToUserFilesOnDisk)
            {
                Response.StatusCode = 500;
                Response.Write("Authentication required - access denied");
                Response.End();
                return;
            }

            try
            {
                HttpPostedFile jpeg_image_upload = Request.Files["Filedata"];

                string dir = "Image/";
                if (Request.QueryString["dir"] != null && Request.QueryString["dir"] != "")
                {
                    dir = Request.QueryString["dir"];
                }

                string baseDir = "~/UserFiles/";

                if (Request.QueryString["DMS"] != null && Request.QueryString["DMS"] == "1")
                {
                    baseDir = CmsConfig.getConfigValue("DMSFileStorageFolderUrl", "");
                    if (!baseDir.EndsWith("/"))
                    {
                        baseDir += "/";
                    }
                }

                string fullDir = System.Web.Hosting.HostingEnvironment.MapPath(baseDir + dir);

                if (!fullDir.EndsWith(Path.DirectorySeparatorChar.ToString()))
                {
                    fullDir += Path.DirectorySeparatorChar;
                }

                string fullFilename = fullDir + Path.GetFileName(jpeg_image_upload.FileName);

                jpeg_image_upload.SaveAs(fullFilename);

                CmsLocalFileOnDisk r = CmsLocalFileOnDisk.CreateFromFile(fullFilename);
                bool b = r.SaveToDatabase();
                if (b)
                {
                    Response.StatusCode = 200;
                    Response.Write(Path.GetFileName(fullFilename));
                    Response.End();
                    return;
                }
            }
            catch (Exception ex)
            {
                Console.Write(ex.Message);
            }
            // If any kind of error occurs return a 500 Internal Server error
            Response.StatusCode = 500;
            Response.Write("An error occured");
            Response.End();
        }
コード例 #20
0
        public void ProcessRequest(HttpContext context)
        {
            IUser  user = Users.GetUser(0, Users.GetLoggedOnUsername(), true, true);
            string str  = "AdvertImg";

            if ((!HiContext.Current.Context.User.IsInRole("manager") && !HiContext.Current.Context.User.IsInRole("systemadministrator")) && ((user.UserRole != UserRole.Distributor) && (user.UserRole != UserRole.SiteManager)))
            {
                this.showError("您没有权限执行此操作");
            }
            else
            {
                if (context.Request.Form["fileCategory"] != null)
                {
                    str = context.Request.Form["fileCategory"];
                }
                string str2 = string.Empty;
                if (context.Request.Form["imgTitle"] != null)
                {
                    str2 = context.Request.Form["imgTitle"];
                }
                this.savePath = string.Format("{0}/UploadImage/" + str + "/", HiContext.Current.GetSkinPath());
                if (context.Request.ApplicationPath != "/")
                {
                    this.saveUrl = this.savePath.Substring(context.Request.ApplicationPath.Length);
                }
                else
                {
                    this.saveUrl = this.savePath;
                }
                HttpPostedFile imgFile = context.Request.Files["imgFile"];
                string         dirPath = "";
                if (this.CheckUploadFile(imgFile, ref dirPath))
                {
                    if (!Directory.Exists(dirPath))
                    {
                        Directory.CreateDirectory(dirPath);
                    }
                    string fileName = imgFile.FileName;
                    if (str2.Length == 0)
                    {
                        str2 = fileName;
                    }
                    string str5     = Path.GetExtension(fileName).ToLower();
                    string str6     = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + str5;
                    string filename = dirPath + str6;
                    string str8     = this.saveUrl + str6;
                    try
                    {
                        imgFile.SaveAs(filename);
                        Hashtable hashtable = new Hashtable();
                        hashtable["error"] = 0;
                        hashtable["url"]   = Globals.ApplicationPath + str8;
                        this.message       = JsonMapper.ToJson(hashtable);
                    }
                    catch
                    {
                        this.showError("保存文件出错");
                    }
                }
            }
            context.Response.ContentType = "text/html";
            context.Response.Write(this.message);
        }
コード例 #21
0
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/html";
            CommonHelper.IsLogin();
            bool isSave = !String.IsNullOrEmpty(context.Request["save"]);

            if (isSave)
            {
                HttpPostedFile huihui_pic = context.Request.Files["huihui_pic"];

                if (context.Request["CN_Name"] != "")
                {
                    CommonHelper.WriteSetting("CN_Name", context.Request["CN_Name"]);
                }
                if (context.Request["EN_Name"] != "")
                {
                    CommonHelper.WriteSetting("EN_Name", context.Request["EN_Name"]);
                }
                if (context.Request["Address"] != "")
                {
                    CommonHelper.WriteSetting("Address", context.Request["Address"]);
                }
                if (context.Request["postCode"] != "")
                {
                    CommonHelper.WriteSetting("postCode", context.Request["postCode"]);
                }
                if (context.Request["linkMan"] != "")
                {
                    CommonHelper.WriteSetting("linkMan", context.Request["linkMan"]);
                }
                if (context.Request["tel"] != "")
                {
                    CommonHelper.WriteSetting("tel", context.Request["tel"]);
                }
                if (context.Request["QQ"] != "")
                {
                    CommonHelper.WriteSetting("QQ", context.Request["QQ"]);
                }
                if (context.Request["Email"] != "")
                {
                    CommonHelper.WriteSetting("Email", context.Request["Email"]);
                }
                if (context.Request["weChat"] != "" || context.Request["QQ_qun"] != "" || context.Request["microBlog"] != "")
                {
                    CommonHelper.WriteSetting("weChat", context.Request["weChat"]);
                    CommonHelper.WriteSetting("QQ_qun", context.Request["QQ_qun"]);
                    CommonHelper.WriteSetting("microBlog", context.Request["microBlog"]);
                }
                if (context.Request["phone"] != "")
                {
                    CommonHelper.WriteSetting("phone", context.Request["phone"]);
                }
                CommonHelper.WriteSetting("guestbook", context.Request["guestbook"]);

                if (CommonHelper.HasFile(huihui_pic))
                {
                    string huihuiName = DateTime.Now.ToString("yyyyMMddHHmmssfffffff") + Path.GetExtension(huihui_pic.FileName);
                    huihui_pic.SaveAs(context.Server.MapPath("~/uploadfile/" + huihuiName));
                    CommonHelper.WriteSetting("huihui_pic", "/uploadfile/" + huihuiName);
                }

                context.Response.Redirect("setting.ashx");
            }
            else
            {
                context.Response.Write(CommonHelper.RenderHtml("Admin/setting.html", new { Title = "网站配置", setting = CommonHelper.GetSetting(), settings = CommonHelper.GetSetting() }));
            }
        }
        public override void SendResponse(System.Web.HttpResponse response)
        {
            int    iErrorNumber = 0;
            string sFileName    = "";

            try
            {
                this.CheckConnector();
                this.CheckRequest();

                if (!this.CurrentFolder.CheckAcl(AccessControlRules.FileUpload))
                {
                    ConnectorException.Throw(Errors.Unauthorized);
                }

                HttpPostedFile oFile = HttpContext.Current.Request.Files["NewFile"];

                if (oFile != null)
                {
                    sFileName = System.IO.Path.GetFileName(oFile.FileName);
                    if (Connector.CheckFileName(sFileName) && !Config.Current.CheckIsHiddenFile(sFileName))
                    {
                        // Replace dots in the name with underscores (only one dot can be there... security issue).
                        if (Config.Current.ForceSingleExtension)
                        {
                            sFileName = Regex.Replace(sFileName, @"\.(?![^.]*$)", "_", RegexOptions.None);
                        }

                        if (!Config.Current.CheckSizeAfterScaling && this.CurrentFolder.ResourceTypeInfo.MaxSize > 0 && oFile.ContentLength > this.CurrentFolder.ResourceTypeInfo.MaxSize)
                        {
                            ConnectorException.Throw(Errors.UploadedTooBig);
                        }

                        string sExtension = System.IO.Path.GetExtension(oFile.FileName);
                        sExtension = sExtension.TrimStart('.');

                        if (!this.CurrentFolder.ResourceTypeInfo.CheckExtension(sExtension))
                        {
                            ConnectorException.Throw(Errors.InvalidExtension);
                        }

                        if (Config.Current.CheckIsNonHtmlExtension(sExtension) && !this.CheckNonHtmlFile(oFile))
                        {
                            ConnectorException.Throw(Errors.UploadedWrongHtmlFile);
                        }

                        // Map the virtual path to the local server path.
                        string sServerDir = this.CurrentFolder.ServerPath;

                        string sFileNameNoExt = System.IO.Path.GetFileNameWithoutExtension(sFileName);

                        int iCounter = 0;

                        while (true)
                        {
                            string sFilePath = System.IO.Path.Combine(sServerDir, sFileName);

                            if (System.IO.File.Exists(sFilePath))
                            {
                                iCounter++;
                                sFileName =
                                    sFileNameNoExt +
                                    "(" + iCounter + ")" +
                                    System.IO.Path.GetExtension(oFile.FileName);

                                iErrorNumber = Errors.UploadedFileRenamed;
                            }
                            else
                            {
                                oFile.SaveAs(sFilePath);

                                if (Config.Current.SecureImageUploads && ImageTools.IsImageExtension(sExtension) && !ImageTools.ValidateImage(sFilePath))
                                {
                                    System.IO.File.Delete(sFilePath);
                                    ConnectorException.Throw(Errors.UploadedCorrupt);
                                }

                                Settings.Images imagesSettings = Config.Current.Images;

                                if (imagesSettings.MaxHeight > 0 && imagesSettings.MaxWidth > 0)
                                {
                                    ImageTools.ResizeImage(sFilePath, sFilePath, imagesSettings.MaxWidth, imagesSettings.MaxHeight, true, imagesSettings.Quality);

                                    if (Config.Current.CheckSizeAfterScaling && this.CurrentFolder.ResourceTypeInfo.MaxSize > 0)
                                    {
                                        long fileSize = new System.IO.FileInfo(sFilePath).Length;
                                        if (fileSize > this.CurrentFolder.ResourceTypeInfo.MaxSize)
                                        {
                                            System.IO.File.Delete(sFilePath);
                                            ConnectorException.Throw(Errors.UploadedTooBig);
                                        }
                                    }
                                }

                                break;
                            }
                        }
                    }
                    else
                    {
                        ConnectorException.Throw(Errors.InvalidName);
                    }
                }
                else
                {
                    ConnectorException.Throw(Errors.UploadedCorrupt);
                }
            }
            catch (ConnectorException connectorException)
            {
                iErrorNumber = connectorException.Number;
            }
            catch
            {
                iErrorNumber = Errors.Unknown;
            }

            response.Clear();

            response.Write("<script type=\"text/javascript\">");
            response.Write(this.GetJavaScriptCode(iErrorNumber, sFileName, this.CurrentFolder.Url + sFileName));
            response.Write("</script>");

            response.End();
        }
コード例 #23
0
        public void ProcessRequest(HttpContext context)
        {
            MyClass Fn      = new MyClass();
            var     frmdata = context.Request.Form["vls"];

            string[] d  = frmdata.Split('½');
            int      ID = Convert.ToInt32(d[5]);

            try
            {
                if (ID > 0)
                {
                    int NewEmpID = ID;
                    if (context.Request.Files.Count > 0 && NewEmpID > 0)
                    {
                        HttpFileCollection SelectedFiles = context.Request.Files;

                        for (int i = 0; i < SelectedFiles.Count; i++)
                        {
                            // Start
                            HttpPostedFile PostedFile = SelectedFiles[i];
                            string         FileName   = context.Server.MapPath("~/Uploads/EstateCandidatePhoto/" + PostedFile.FileName);
                            string         Path       = context.Server.MapPath("~/Uploads/EstateCandidatePhoto/");
                            FileInfo       fi         = new FileInfo(FileName);

                            var x = "update tbl_EstateApplicant set Name = '" + d[0] + "', CNIC = '" + d[1] + "', NTN = '" + d[2] + "', ContactNo = '" + d[3] + "', Address = '" + d[4] + "', PhotoExtension = '" + fi.Extension + "' where ApplicantID = " + NewEmpID;
                            Fn.Exec(x);

                            PostedFile.SaveAs(Path + Convert.ToString(NewEmpID) + fi.Extension);
                        }
                    }

                    if (NewEmpID > 0)
                    {
                        context.Response.ContentType = "text/plain";
                        context.Response.Write(NewEmpID);
                    }
                }
                else
                {
                    string id = "";
                    id = Fn.ExenID(@"INSERT INTO tbl_EstateApplicant (Name, CNIC, NTN, ContactNo, Address) VALUES ('" + d[0] + "', '" + d[1] + "','" + d[2] + "', '" + d[3] + "', '" + d[4] + "'); Select Scope_Identity();");



                    int NewEmpID = Convert.ToInt32(id);
                    if (context.Request.Files.Count > 0 && NewEmpID > 0)
                    {
                        HttpFileCollection SelectedFiles = context.Request.Files;

                        for (int i = 0; i < SelectedFiles.Count; i++)
                        {
                            // Start
                            HttpPostedFile PostedFile = SelectedFiles[i];
                            string         FileName   = context.Server.MapPath("~/Uploads/EstateCandidatePhoto/" + PostedFile.FileName);
                            string         Path       = context.Server.MapPath("~/Uploads/EstateCandidatePhoto/");
                            FileInfo       fi         = new FileInfo(FileName);

                            Fn.Exec("update tbl_EstateApplicant set PhotoExtension = '" + fi.Extension + "' where ApplicantID = " + NewEmpID);

                            PostedFile.SaveAs(Path + Convert.ToString(NewEmpID) + fi.Extension);
                        }
                    }

                    if (NewEmpID > 0)
                    {
                        context.Response.ContentType = "text/plain";
                        context.Response.Write(NewEmpID);
                    }
                }
            }
            catch (Exception ex)
            {
                context.Response.ContentType = "text/plain";
                context.Response.Write(ex.Message);
            }
        }
コード例 #24
0
        public void CargaExcelPuntosOrigenDestino()
        {
            HttpContext context = HttpContext.Current;

            if (context.Request.Files.Count > 0)
            {
                DataTable dt = new DataTable();
                dt.Columns.Add("LatOrigen", typeof(string));
                dt.Columns.Add("LonOrigen", typeof(string));
                dt.Columns.Add("LatDestino", typeof(string));
                dt.Columns.Add("LonDestino", typeof(string));

                HttpPostedFile archivoSubido = context.Request.Files[0];
                StreamReader   file          = new StreamReader(context.Request.Files[0].InputStream);

                string[] fileName      = archivoSubido.FileName.Split('.');
                string   fileExtension = fileName[fileName.Length - 1].ToUpper();
                string   rutaSitio     = Utilities.GetExePath();

                if (!(Directory.Exists(rutaSitio + "FileTemp")))
                {
                    Directory.CreateDirectory(rutaSitio + "FileTemp");
                }
                string Fechafile    = DateTime.Now.ToString("ddMMyyyyHHmmss");
                var    fileNameCopy = @"" + rutaSitio + "FileTemp\\ExcelTemp" + Fechafile + "." + fileExtension;
                string result       = "";
                try
                {
                    if (fileExtension == "XLS" || fileExtension == "XLSX" || fileExtension == "XLSB")
                    {
                        archivoSubido.SaveAs(fileNameCopy);
                        ExcelQueryFactory xcl = new ExcelQueryFactory(fileNameCopy);
                        var lst = from d in xcl.Worksheet(0) select d;

                        if (lst.ToList()[0][0].ToString() != "Latitud Origen" || lst.ToList()[0][1].ToString() != "Longitud Origen" || lst.ToList()[0][2].ToString() != "Latitud Destino" || lst.ToList()[0][3].ToString() != "Longitud Destino")
                        {
                            result = @"{'success':true,'Data':[], 'result':false}";
                        }
                        else
                        {
                            {
                                DataRow rowNew;

                                for (int i = 1; i < lst.ToList().Count; i++)
                                {
                                    rowNew = dt.NewRow();

                                    rowNew[0] = lst.ToList()[i][0].ToString();
                                    rowNew[1] = lst.ToList()[i][1].ToString();
                                    rowNew[2] = lst.ToList()[i][2].ToString();
                                    rowNew[3] = lst.ToList()[i][3].ToString();

                                    dt.Rows.Add(rowNew);
                                }
                                result = @"{'success':true,'Data':[" + JsonConvert.SerializeObject(dt) + "], 'result':true}";
                            }
                        }
                    }

                    Response.Write(result);
                }
                catch (Exception)
                {
                    result = @"{'success':true,'Data':[" + JsonConvert.SerializeObject(dt) + "], 'result':false}";
                    Response.Write(result);
                }
            }
        }
コード例 #25
0
        public void ProcessRequest(HttpContext context)
        {
            //string RestaurantMenuPkID = context.Request.QueryString["RestaurantMenuPkID"].ToString();
            //string ext = "asdf";
            //string XML = "<NewDataSet><BusinessObject><RestaurantMenuPkID>" + RestaurantMenuPkID + "</RestaurantMenuPkID><ImageFileExt>" + ext + "</ImageFileExt></BusinessObject></NewDataSet>";
            //SystemGlobals.DataBase.ExecuteQuery("spres_RestaurantMenuImage_UPD", XML);

            if (context.Request.Files.Count > 0)
            {
                if (context.Request.QueryString["RestaurantMenuPkID"] != null)
                {
                    string             RestaurantMenuPkID      = context.Request.QueryString["RestaurantMenuPkID"].ToString();
                    HttpFileCollection UploadedFilesCollection = context.Request.Files;
                    for (int i = 0; i < UploadedFilesCollection.Count; i++)
                    {
                        string ext = Path.GetExtension(UploadedFilesCollection[i].FileName);

                        HttpPostedFile PostedFiles = UploadedFilesCollection[i];

                        string XML = "<NewDataSet><BusinessObject><RestaurantMenuPkID>" + RestaurantMenuPkID + "</RestaurantMenuPkID><ImageFileExt>" + ext + "</ImageFileExt></BusinessObject></NewDataSet>";
                        SystemGlobals.DataBase.ExecuteQuery("spres_RestaurantMenuImage_UPD", XML);

                        string FilePath = context.Server.MapPath("/upload/menu/" + RestaurantMenuPkID + ext);

                        PostedFiles.SaveAs(FilePath);
                    }
                }

                if (context.Request.QueryString["RestaurantPkID"] != null)
                {
                    string             RestaurantPkID          = context.Request.QueryString["RestaurantPkID"].ToString();
                    HttpFileCollection UploadedFilesCollection = context.Request.Files;
                    for (int i = 0; i < UploadedFilesCollection.Count; i++)
                    {
                        string ext = Path.GetExtension(UploadedFilesCollection[i].FileName);

                        HttpPostedFile PostedFiles = UploadedFilesCollection[i];

                        string XML = "<NewDataSet><BusinessObject><RestaurantPkID>" + RestaurantPkID + "</RestaurantPkID><ImageFileExt>" + ext + "</ImageFileExt></BusinessObject></NewDataSet>";
                        SystemGlobals.DataBase.ExecuteQuery("spres_RestaurantImage_UPD", XML);

                        string FilePath = context.Server.MapPath("/upload/restaurant/" + RestaurantPkID + ext);

                        PostedFiles.SaveAs(FilePath);
                    }
                }

                if (context.Request.QueryString["DocumentPkID"] != null)
                {
                    string             DocumentPkID            = context.Request.QueryString["DocumentPkID"].ToString();
                    HttpFileCollection UploadedFilesCollection = context.Request.Files;
                    for (int i = 0; i < UploadedFilesCollection.Count; i++)
                    {
                        string ext = Path.GetExtension(UploadedFilesCollection[i].FileName);

                        HttpPostedFile PostedFiles = UploadedFilesCollection[i];

                        string XML = "<NewDataSet><BusinessObject><DocumentPkID>" + DocumentPkID + "</DocumentPkID><ImageFileExt>" + ext + "</ImageFileExt></BusinessObject></NewDataSet>";
                        SystemGlobals.DataBase.ExecuteQuery("spint_docDocumentImage_UPD", XML);

                        string FilePath = context.Server.MapPath("/upload/document/" + DocumentPkID + ext);

                        PostedFiles.SaveAs(FilePath);
                    }
                }

                if (context.Request.QueryString["CommentPkID"] != null)
                {
                    string             CommentPkID             = context.Request.QueryString["CommentPkID"].ToString();
                    HttpFileCollection UploadedFilesCollection = context.Request.Files;
                    for (int i = 0; i < UploadedFilesCollection.Count; i++)
                    {
                        string ext = Path.GetExtension(UploadedFilesCollection[i].FileName);

                        HttpPostedFile PostedFiles = UploadedFilesCollection[i];

                        string XML = "<NewDataSet><BusinessObject><CommentPkID>" + CommentPkID + "</CommentPkID><ImageFileExt>" + ext + "</ImageFileExt></BusinessObject></NewDataSet>";
                        SystemGlobals.DataBase.ExecuteQuery("spint_docDocumentCommentImage_UPD", XML);

                        string FilePath = context.Server.MapPath("/upload/document/comment/" + CommentPkID + ext);

                        PostedFiles.SaveAs(FilePath);
                    }
                }
            }
        }
コード例 #26
0
        public void SaveUploadedFile(HttpFileCollection httpFileCollection)
        {
            // Clear Session data if no file uploades are made (IsPostBack does not work, need to clear session data on page re-load)
            List <FileAttachment> fileAttachments = new List <FileAttachment>();

            if (httpFileCollection.Count == 0)
            {
                // Delete previously uploaded files in SESSION to be erased
                fileAttachments = (List <FileAttachment>)Session["UPLOADED_QUOTE"];
                if (fileAttachments != null && fileAttachments.Count > 0)
                {
                    foreach (var file in fileAttachments)
                    {
                        FileInfo TheFile = new FileInfo(file.path);
                        if (TheFile.Exists)
                        {
                            // File found so delete it.
                            TheFile.Delete();
                        }
                    }
                }

                Session["UPLOADED_QUOTE"] = null;
            }
            fileAttachments = (List <FileAttachment>)Session["UPLOADED_QUOTE"];

            string fName = "";

            foreach (string fileName in httpFileCollection)
            {
                HttpPostedFile file = httpFileCollection.Get(fileName);
                //Save file content goes here
                fName = file.FileName;
                if (file != null && file.ContentLength > 0)
                {
                    var originalDirectory = new DirectoryInfo(string.Format("{0}", Server.MapPath(@"\")));

                    string pathString = System.IO.Path.Combine(originalDirectory.ToString(), "ClientUploadedFiles");

                    var fileName1 = Path.GetFileName(file.FileName);


                    bool isExists = System.IO.Directory.Exists(pathString);

                    if (!isExists)
                    {
                        System.IO.Directory.CreateDirectory(pathString);
                    }

                    var path = string.Format("{0}\\{1}", pathString, file.FileName);

                    // Get file attachments
                    if (fileAttachments == null)
                    {
                        fileAttachments = new List <FileAttachment>();
                    }

                    fileAttachments.Add(new FileAttachment()
                    {
                        name = fileName1, target_name = fileName1, size = file.ContentLength, path = path
                    });
                    Session["UPLOADED_QUOTE"] = fileAttachments;
                    file.SaveAs(path);
                }
            }
        }
コード例 #27
0
        //班组长导入
        protected void QueryButton2_Click(object sender, EventArgs e)
        {
            List <string> list001 = new List <string>();

            if (tb_yearmonth2.Text.ToString().Trim() == "")
            {
                ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "", "alert('请填写年月!');", true);
                ModalPopupExtenderSearch.Hide();
                return;
            }
            string sqlifscgz = "select * from OM_GZHSB where GZ_YEARMONTH='" + tb_yearmonth2.Text.ToString().Trim() + "' and (OM_GZSCBZ='0' or OM_GZSCBZ='1')";

            System.Data.DataTable dtisscgz = DBCallCommon.GetDTUsingSqlText(sqlifscgz);
            if (dtisscgz.Rows.Count > 0)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "", "alert('该月已生成工资!!!');", true);
                ModalPopupExtenderSearch.Hide();
                return;
            }
            string sqlifspz = "select * from OM_SCCZSH_TOTAL where TOLTYPE='1' and (SCCZTOL_TOLSTATE='1' or SCCZTOL_TOLSTATE='2') and SCCZTOL_NY='" + tb_yearmonth2.Text.Trim() + "'";

            System.Data.DataTable dtifspz = DBCallCommon.GetDTUsingSqlText(sqlifspz);
            if (dtifspz.Rows.Count > 0)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "", "alert('该月已有数据审批中或已通过!!!');", true);
                ModalPopupExtenderSearch.Hide();
                return;
            }
            string sqlwtj = "select * from OM_SCCZSH_TOTAL where SCCZTOL_TOLSTATE='0' and TOLTYPE='1' and SCCZTOL_NY='" + tb_yearmonth2.Text.Trim() + "'";

            System.Data.DataTable dtwtj = DBCallCommon.GetDTUsingSqlText(sqlwtj);
            if (dtwtj.Rows.Count > 0)
            {
                string sqldelete0 = "delete from OM_SCCZSH_TOTAL where SCCZTOL_TOLSTATE='0' and TOLTYPE='1' and SCCZTOL_NY='" + tb_yearmonth2.Text.Trim() + "'";
                list001.Add(sqldelete0);
                for (int n = 0; n < dtwtj.Rows.Count; n++)
                {
                    string sqldelete1 = "delete from OM_SCCZ_FZBZ where TYPE='1' and FZBZ_BH='" + dtwtj.Rows[n]["SCCZTOL_BH"].ToString().Trim() + "'";
                    list001.Add(sqldelete1);
                }
                DBCallCommon.ExecuteTrans(list001);
            }
            List <string> list     = new List <string>();
            string        bz_bh    = "BZ" + DateTime.Now.ToString("yyyyMMddHHmmss").Trim() + Session["UserID"].ToString().Trim();
            string        FilePath = @"E:\班组岗位绩效表班组长\";

            if (!Directory.Exists(FilePath))
            {
                Directory.CreateDirectory(FilePath);
            }
            //将文件上传到服务器
            HttpPostedFile UserHPF = FileUpload2.PostedFile;

            try
            {
                string fileContentType = UserHPF.ContentType;// 获取客户端发送的文件的 MIME 内容类型
                if (fileContentType == "application/vnd.ms-excel")
                {
                    if (UserHPF.ContentLength > 0)
                    {
                        UserHPF.SaveAs(FilePath + "//" + System.IO.Path.GetFileName(UserHPF.FileName));//将上传的文件存放在指定的文件夹中
                    }
                }
                else
                {
                    ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "", "alert('文件类型不符合要求,请您核对后重新上传!');", true);
                    ModalPopupExtenderSearch.Hide();
                    return;
                }
            }
            catch
            {
                ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "", "alert('文件上传过程中出现错误!');", true);
                ModalPopupExtenderSearch.Hide();
                return;
            }


            using (FileStream fs = File.OpenRead(FilePath + "//" + System.IO.Path.GetFileName(UserHPF.FileName)))
            {
                //根据文件流创建一个workbook
                IWorkbook wk = new HSSFWorkbook(fs);

                //获取第一个工作表
                ISheet sheet1 = wk.GetSheetAt(0);
                for (int i = 2; i < sheet1.LastRowNum + 1; i++)
                {
                    string stidfzbz     = "";
                    IRow   rowfzbz      = sheet1.GetRow(i);
                    ICell  cellfzbz01   = rowfzbz.GetCell(1);
                    string strnamecheck = "";
                    try
                    {
                        strnamecheck = cellfzbz01.ToString().Trim();
                    }
                    catch
                    {
                        strnamecheck = "";
                    }
                    if (strnamecheck != "")
                    {
                        string sqlfzbz = "select ST_ID from TBDS_STAFFINFO where ST_NAME='" + strnamecheck + "'";
                        System.Data.DataTable dtfzbz = DBCallCommon.GetDTUsingSqlText(sqlfzbz);
                        if (dtfzbz.Rows.Count > 0)
                        {
                            string sqlfzbzinsert = "";
                            stidfzbz      = dtfzbz.Rows[0]["ST_ID"].ToString().Trim();
                            sqlfzbzinsert = "'" + bz_bh + "','" + stidfzbz + "','" + tb_yearmonth2.Text.ToString().Trim() + "'";
                            for (int k = 23; k < 27; k++)
                            {
                                string strfzbz  = "";
                                ICell  cellfzbz = rowfzbz.GetCell(k);
                                try
                                {
                                    strfzbz = cellfzbz.NumericCellValue.ToString().Trim();
                                }
                                catch
                                {
                                    try
                                    {
                                        strfzbz = cellfzbz.ToString().Trim();
                                    }
                                    catch
                                    {
                                        strfzbz = "";
                                    }
                                }
                                sqlfzbzinsert += ",'" + CommonFun.ComTryDecimal(strfzbz) + "'";
                            }
                            sqlfzbzinsert += ",'1'";
                            string sqltextfzbzinsert = "insert into OM_SCCZ_FZBZ(FZBZ_BH,FZBZ_STID,FZBZ_YEARMONTH,FZBZ_JXGZ,FZBZ_GWGZ,FZBZ_QT,FZBZ_JBGZ,TYPE) values(" + sqlfzbzinsert + ")";
                            list.Add(sqltextfzbzinsert);
                        }
                    }
                    else
                    {
                        break;
                    }
                }
            }
            string sqltotal = "insert into OM_SCCZSH_TOTAL(SCCZTOL_BH,SCCZTOL_NY,SCCZTOL_ZDRID,SCCZTOL_ZDRNAME,SCCZTOL_ZDTIME,SCCZTOL_TOLSTATE,SCCZTOL_NOTE,TOLTYPE) values('" + bz_bh + "','" + tb_yearmonth2.Text.Trim() + "','" + Session["UserID"].ToString().Trim() + "','" + Session["UserName"].ToString().Trim() + "','" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "','0','" + tb_NOTE2.Text.Trim() + "','1')";

            list.Add(sqltotal);
            DBCallCommon.ExecuteTrans(list);

            foreach (string fileName in Directory.GetFiles(FilePath))//清空该文件夹下的文件
            {
                string newName = fileName.Substring(fileName.LastIndexOf("\\") + 1);
                System.IO.File.Delete(FilePath + "\\" + newName);//删除文件下储存的文件
            }
            UCPaging1.CurrentPage = 1;
            bindrpt();
            Response.Redirect("OM_SCCZSP_DETAIL.aspx?bh=" + bz_bh);
        }
コード例 #28
0
        public void ProcessRequest(HttpContext context)
        {
            String aspxUrl = context.Request.Path.Substring(0, context.Request.Path.LastIndexOf("/") + 1);

            //文件保存目录路径
            String savePath = "/FileSavePath/";

            //文件保存目录URL
            String saveUrl = "/FileSavePath/";

            //定义允许上传的文件扩展名
            Hashtable extTable = new Hashtable();

            extTable.Add("flash", "swf,flv");
            extTable.Add("media", "mp3,wmv,avi,rmvb");
            extTable.Add("file", "doc,docx,xls,xlsx,ppt,pdf,txt,html,txt,zip,rar");

            //最大文件大小
            int maxSize = 2000000;

            this.context = context;

            HttpPostedFile imgFile = context.Request.Files["files"];

            if (imgFile == null)
            {
                showError("请选择文件。");
            }

            String dirPath = context.Server.MapPath(savePath);

            if (!Directory.Exists(dirPath))
            {
                showError("上传目录不存在。");
            }
            string dirName  = "";
            String fileName = imgFile.FileName;
            String fileExt  = Path.GetExtension(fileName).ToLower();

            if (CheckFileExt(fileExt) != "")
            {
                dirName = CheckFileExt(fileExt);
            }

            if (String.IsNullOrEmpty(dirName))
            {
                dirName = "file";
            }
            if (!extTable.ContainsKey(dirName))
            {
                showError("目录名不正确。");
            }



            if (imgFile.InputStream == null || imgFile.InputStream.Length > maxSize)
            {
                showError("上传文件大小超过限制。");
            }

            if (String.IsNullOrEmpty(fileExt) || Array.IndexOf(((String)extTable[dirName]).Split(','), fileExt.Substring(1).ToLower()) == -1)
            {
                showError("上传文件扩展名是不允许的扩展名。\n只允许" + ((String)extTable[dirName]) + "格式。");
            }

            //创建文件夹
            dirPath += dirName + "/";
            saveUrl += dirName + "/";
            if (!Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath);
            }
            String ymd = DateTime.Now.ToString("yyyyMMdd", DateTimeFormatInfo.InvariantInfo);

            dirPath += ymd + "/";
            saveUrl += ymd + "/";
            if (!Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath);
            }

            String newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + fileExt;
            String filePath    = dirPath + newFileName;

            imgFile.SaveAs(filePath);

            String fileUrl = saveUrl + newFileName;

            //构造输出显示的model
            //FileDescription fileDes = new FileDescription();
            //fileDes.FileName = Path.GetFileNameWithoutExtension(fileName);
            //fileDes.FileSize = (imgFile.ContentLength / 1024).ToString()+"KB";
            //fileDes.FileTime = DateTime.Now.ToString();
            //fileDes.FileSavePath =filePath;
            //fileDes.FileExt = fileExt;
            //构造插入内容
            T_File model = new T_File();

            model.FileId      = bll.GetIdByTime(DateTime.Now.ToString("yyyyMMdd"));
            model.FileName    = fileName;
            model.FilePath    = fileUrl;
            model.FileExt     = fileExt;
            model.FileSector  = "";//(context.Session["model"] as T_InfoAdmin).InfoAdminSector;
            model.FileSummary = context.Request["summary"];
            model.FileTime    = DateTime.Now.ToString();
            model.FileSector  = "liushangnan";
            bll.Insert(model);
            context.Response.Write("添加成功,请关闭此窗口~");
        }
コード例 #29
0
ファイル: UpLoad.cs プロジェクト: sichina/DTcms_103_sql_src
        /// <summary>
        /// 文件上传方法B
        /// </summary>
        /// <param name="postedFile">文件流</param>
        /// <param name="isThumbnail">是否生成缩略图</param>
        /// <param name="isWater">是否打水印</param>
        /// <param name="isWater">是否返回文件原名称</param>
        /// <returns>服务器文件路径</returns>
        public string fileSaveAs(HttpPostedFile postedFile, bool isThumbnail, bool isWater, bool _isReOriginal)
        {
            try
            {
                string fileExt          = postedFile.FileName.Substring(postedFile.FileName.LastIndexOf(".") + 1);  //文件扩展名,不含“.”
                string originalFileName = postedFile.FileName.Substring(postedFile.FileName.LastIndexOf(@"\") + 1); //取得文件原名
                string fileName         = Utils.GetRamCode() + "." + fileExt;                                       //随机文件名
                string dirPath          = GetUpLoadPath();                                                          //上传目录相对路径

                //检查文件扩展名是否合法
                if (!CheckFileExt(fileExt))
                {
                    return("{msg: 0, msbox: \"不允许上传" + fileExt + "类型的文件!\"}");
                }
                //检查文件大小是否合法
                if (!CheckFileSize(fileExt, postedFile.ContentLength))
                {
                    return("{msg: 0, msbox: \"文件超过限制的大小啦!\"}");
                }
                //获得要保存的文件路径
                string serverFileName          = dirPath + fileName;
                string serverThumbnailFileName = dirPath + "small_" + fileName;
                string returnFileName          = serverFileName;
                //物理完整路径
                string toFileFullPath = Utils.GetMapPath(dirPath);
                //检查有该路径是否就创建
                if (!Directory.Exists(toFileFullPath))
                {
                    Directory.CreateDirectory(toFileFullPath);
                }
                //保存文件
                postedFile.SaveAs(toFileFullPath + fileName);
                //如果是图片,检查图片尺寸是否超出限制
                if (IsImage(fileExt) && (this.siteConfig.attachimgmaxheight > 0 || this.siteConfig.attachimgmaxwidth > 0))
                {
                    Thumbnail.MakeThumbnailImage(toFileFullPath + fileName, toFileFullPath + fileName, this.siteConfig.attachimgmaxwidth, this.siteConfig.attachimgmaxheight);
                }
                //是否生成缩略图
                if (IsImage(fileExt) && isThumbnail && this.siteConfig.thumbnailwidth > 0 && this.siteConfig.thumbnailheight > 0)
                {
                    Thumbnail.MakeThumbnailImage(toFileFullPath + fileName, toFileFullPath + "small_" + fileName, this.siteConfig.thumbnailwidth, this.siteConfig.thumbnailheight, "Cut");
                    returnFileName += "," + serverThumbnailFileName; //返回缩略图,以逗号分隔开
                }
                //是否打图片水印
                if (IsWaterMark(fileExt) && isWater)
                {
                    switch (this.siteConfig.watermarktype)
                    {
                    case 1:
                        WaterMark.AddImageSignText(serverFileName, serverFileName,
                                                   this.siteConfig.watermarktext, this.siteConfig.watermarkposition,
                                                   this.siteConfig.watermarkimgquality, this.siteConfig.watermarkfont, this.siteConfig.watermarkfontsize);
                        break;

                    case 2:
                        WaterMark.AddImageSignPic(serverFileName, serverFileName,
                                                  this.siteConfig.watermarkpic, this.siteConfig.watermarkposition,
                                                  this.siteConfig.watermarkimgquality, this.siteConfig.watermarktransparency);
                        break;
                    }
                }
                //如果需要返回原文件名
                if (_isReOriginal)
                {
                    return("{msg: 1, msbox: \"" + serverFileName + "\", mstitle: \"" + originalFileName + "\"}");
                }
                return("{msg: 1, msbox: \"" + returnFileName + "\"}");
            }
            catch
            {
                return("{msg: 0, msbox: \"上传过程中发生意外错误!\"}");
            }
        }
コード例 #30
0
ファイル: Util.cs プロジェクト: lakeli/shizong
 /// <summary>
 /// IMGPath图路径,pathIndex指定路径前缀
 /// </summary>
 /// <param name="IMGPath"></param>
 /// <param name="Server"></param>
 /// <param name="fu"></param>
 /// <param name="pathIndex"></param>
 public static void uploadIMG(ref string IMGPath, HttpServerUtility Server, HttpPostedFile PostedFile, string FileName, string pathIndex)
 {
     try
     {
         string CurrentDatatime = Convert.ToString(System.DateTime.Now.Year.ToString() + System.DateTime.Now.Month.ToString() + System.DateTime.Now.Day.ToString() + System.DateTime.Now.Minute.ToString() + System.DateTime.Now.Second.ToString() + System.DateTime.Now.Millisecond.ToString());
         IMGPath = pathIndex + CurrentDatatime + FileName.ToString();
         string IMG_FullName = Server.MapPath(pathIndex) + CurrentDatatime + FileName.ToString();
         IMG_FullName = IMG_FullName.Replace("%", "");
         PostedFile.SaveAs(IMG_FullName);
     }
     catch
     {
     }
 }
コード例 #31
0
        /// <summary>
        /// Insert new warning to DB.
        /// </summary>
        public void doInsert(string type, Dictionary <string, string> _ag, string modid, string redirect)
        {
            ///-----------------------------------------
            /// Set variables
            ///-----------------------------------------
            _post_title = Convert.ToString(HttpContext.Current.Request["PostTitle"]);
            _post_type  = Convert.ToString(HttpContext.Current.Request["PostType"]);
            _post_url   = Convert.ToString(HttpContext.Current.Request["PostURL"]);
            _post_text  = Convert.ToString(HttpContext.Current.Request["PostText"]);
            _post_catid = Convert.ToString(HttpContext.Current.Request["CatID"]);
            int filecount = Convert.ToInt32(HttpContext.Current.Request.Files.Count);
            ///-----------------------------------------
            /// Encode HTML tags
            ///-----------------------------------------
            string _post_text_encode = WebUtility.HtmlEncode(_post_text);
            ///-----------------------------------------
            string lastid = string.Empty;

            ///-----------------------------------------
            /// Set up arrays
            ///-----------------------------------------
            string[,] post_data;
            string[,] file_data;
            string ins   = string.Empty;
            string insup = string.Empty;

            ///-----------------------------------------
            if (type == "new")
            {
                _creation_date = Convert.ToString(DateTime.Now);
                _user_id       = _ag["UserID"];
                _mod_id        = modid;

                if (filecount > 0)
                {
                    for (int k = 0; k < HttpContext.Current.Request.Files.Count; k++)
                    {
                        HttpPostedFile ifile = HttpContext.Current.Request.Files[k]; // Get uploaded file
                        _file_name       = Path.GetFileName(ifile.FileName);
                        _file_ext        = Path.GetExtension(ifile.FileName);
                        _file_size       = ifile.ContentLength;
                        _noext_file_name = Path.GetFileNameWithoutExtension(ifile.FileName);
                        _file_ext        = _file_ext.ToLower();
                        ///-----------------------------------------
                        /// Validate uploads
                        ///-----------------------------------------
                        string[] acceptedFileTypes = new string[7];
                        acceptedFileTypes[0] = ".pdf";
                        acceptedFileTypes[1] = ".doc";
                        acceptedFileTypes[2] = ".docx";
                        acceptedFileTypes[3] = ".jpg";
                        acceptedFileTypes[4] = ".jpeg";
                        acceptedFileTypes[5] = ".gif";
                        acceptedFileTypes[6] = ".png";
                        bool acceptFile = false;
                        //should we accept the file?
                        for (int l = 0; l <= 6; l++)
                        {
                            if (_file_ext == acceptedFileTypes[l])
                            {
                                //accept the file, yay!
                                acceptFile = true;
                            }
                        }
                        if (!acceptFile)
                        {
                            string exterr = "The file you are trying to upload is not a permitted file type!";
                            HttpContext.Current.Response.Redirect("~/error.aspx?err=" + exterr + "&color=red");
                        }
                        //Is the file too big to upload?
                        if (_file_size > _max_file_size)
                        {
                            //get Max upload size in MB
                            double maxFileSize = Math.Round(_max_file_size / 1024.0, 1);
                            string sizerr      = "Filesize of the file is too large. Maximum file size permitted is " + maxFileSize + " KB";
                            HttpContext.Current.Response.Redirect("~/error.aspx?err=" + sizerr + "&color=red");
                        }
                    }
                }

                post_data = new string[, ] {
                    { "PostTitle", _post_title },
                    { "PostCreationDate", _creation_date },
                    //{ "PostStartDate", _std },
                    //{ "PostEndDate", _end },
                    { "PostType", _post_type },
                    { "PostURL", _post_url },
                    { "PostText", _post_text_encode },
                    { "UserID", _user_id },
                    { "ModID", _mod_id },
                    { "CatID", _post_catid }
                };

                ins = DB.do_insert("posts", post_data);
                ///---------------------------------------
                /// Insert upload to DB and file to server if posttype is "post"
                ///---------------------------------------
                if (_post_type == "post")
                {
                    ///---------------------------------------
                    /// Get the last ID inserted
                    ///---------------------------------------
                    string        Query = "SELECT MAX(PostID) AS LastID FROM posts";
                    SqlCommand    cmd   = new SqlCommand(Query, con);
                    SqlDataReader r;
                    try
                    {
                        con.Open();
                        r = cmd.ExecuteReader();
                        r.Read();
                        lastid = Convert.ToString(r["LastID"]);
                        r.Close();
                    }
                    catch { }
                    finally { con.Close(); }
                    ///-----------------------------------------
                    /// Manage file to upload
                    ///-----------------------------------------
                    for (int i = 0; i < HttpContext.Current.Request.Files.Count; i++)
                    {
                        HttpPostedFile file = HttpContext.Current.Request.Files[i]; // Get uploaded file
                        if (file.ContentLength > 0)
                        {
                            //saving code here
                            _file_name       = Path.GetFileName(file.FileName);
                            _file_ext        = Path.GetExtension(file.FileName);
                            _file_size       = file.ContentLength;
                            _noext_file_name = Path.GetFileNameWithoutExtension(file.FileName);
                            _file_ext        = _file_ext.ToLower();
                            _new_file_name   = _file_name;
                            string filename_only = string.Empty;
                            int    count         = 1; // Count for new file name if the same name already exists
                            ///---------------------------------------
                            /// Does the file already exist? Change the name to a new one.
                            ///---------------------------------------
                            while (File.Exists(HttpContext.Current.Server.MapPath(Path.Combine("~/uploads/", _new_file_name))))
                            {
                                /*string samerr = "A file with the name " + _file_name + " already exists on the server.";
                                 * HttpContext.Current.Response.Redirect("~/error.aspx?err=" + samerr + "&color=red");*/
                                string tempFileName = string.Format("{0}({1})", _noext_file_name, count++);
                                _new_file_name = tempFileName + _file_ext;
                            }
                            string[] splitFile = _new_file_name.Split('.');
                            filename_only = splitFile[0];
                            ///---------------------------------------
                            /// Set array for file getting last PostID
                            ///---------------------------------------
                            file_data = new string[, ] {
                                { "UFName", filename_only },
                                { "UFCreationDate", _creation_date },
                                { "UFExtension", _file_ext },
                                { "UFSize", Convert.ToString(_file_size) },
                                { "UserID", _user_id },
                                { "PostID", lastid },
                            };

                            if (file != null)
                            {
                                insup = DB.do_insert("uploads", file_data);
                                file.SaveAs(HttpContext.Current.Server.MapPath(Path.Combine("~/uploads/", _new_file_name)));
                            }
                            if (!String.IsNullOrEmpty(insup))
                            {
                                HttpContext.Current.Response.Redirect("~/error.aspx?err=" + insup + "&color=red");
                            }
                        }
                    }
                }

                ///---------------------------------------
                /// Insert log into db
                ///---------------------------------------
                std.save_log(_ag["UserID"], "A new post has been inserted.", "Posts");
            }
            else
            {
                post_data = new string[, ] {
                    { "PostTitle", _post_title },
                    //{ "PostStartDate", _std },
                    //{ "PostEndDate", _end },
                    { "PostType", _post_type },
                    { "PostURL", _post_url },
                    { "PostText", _post_text_encode },
                    { "CatID", _post_catid }
                };

                ins = DB.do_update("posts", post_data, "PostID=" + HttpContext.Current.Request["pid"]);
                ///---------------------------------------
                /// Insert log into db
                ///---------------------------------------
                std.save_log(_ag["UserID"], "The post with id:" + HttpContext.Current.Request["pid"] + " has been modified.", "Posts");
            }

            if (String.IsNullOrEmpty(ins))
            {
                HttpContext.Current.Response.Redirect(redirect);
            }
            else
            {
                HttpContext.Current.Response.Redirect("~/error.aspx?err=" + ins + "&color=red");
            }
            //LoadContent.Text = skin.error_page(colors[_wlColor], "red");
        }
コード例 #32
0
    public string UploadImage(HttpPostedFile fileToUpload, string outputPath, int newWidth, bool randomFileName)
    {
        string strFileName;
        string strLongFilePath = fileToUpload.FileName;
        string ext = Path.GetExtension(strLongFilePath).ToLower();
        var imgFor = GetFormat(ext);

        if (imgFor != null)
        {

            strFileName = Path.GetFileName(strLongFilePath);

            if (randomFileName)
            {
                strFileName = GenRndName() + Path.GetExtension(strFileName);
            }
            else
            {
                strFileName = ReplaceChars(strFileName);
            }

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

            fileToUpload.SaveAs(outputPath + strFileName);

            if (newWidth > 0)
            {
                this.ReSizeImage(outputPath + strFileName, outputPath, newWidth);
            }

            else
            {
                return strFileName;
            }
            return strFileName;
        }
        else
        {
            return null;
        }
    }
コード例 #33
0
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            string   username    = Request.Cookies["userLoginSystem"].Value;
            var      acc         = AccountController.GetByUsername(username);
            DateTime currentDate = DateTime.Now;

            if (acc != null)
            {
                if (acc.RoleID == 0 || acc.RoleID == 1)
                {
                    int cateID = hdfParentID.Value.ToInt();
                    if (cateID > 0)
                    {
                        string ProductSKU   = txtProductSKU.Text.Trim().ToUpper();
                        var    check        = true;
                        var    productcheck = ProductController.GetBySKU(ProductSKU);
                        if (productcheck != null)
                        {
                            check = false;
                        }
                        else
                        {
                            var productvariable = ProductVariableController.GetBySKU(ProductSKU);
                            if (productvariable != null)
                            {
                                check = false;
                            }
                        }

                        if (check == false)
                        {
                            PJUtils.ShowMessageBoxSwAlert("Trùng mã sản phẩm vui lòng kiểm tra lại", "e", false, Page);
                        }
                        else
                        {
                            string ProductTitle   = txtProductTitle.Text.ToString();
                            string ProductContent = pContent.Content.ToString();

                            double ProductStock  = 0;
                            int    StockStatus   = 3;
                            double Regular_Price = Convert.ToDouble(pRegular_Price.Text);
                            double CostOfGood    = Convert.ToDouble(pCostOfGood.Text);
                            double Retail_Price  = Convert.ToDouble(pRetailPrice.Text);
                            int    supplierID    = ddlSupplier.SelectedValue.ToInt(0);
                            string supplierName  = ddlSupplier.SelectedItem.ToString();
                            int    a             = 1;

                            double MinimumInventoryLevel = pMinimumInventoryLevel.Text.ToInt(0);
                            double MaximumInventoryLevel = pMaximumInventoryLevel.Text.ToInt(0);

                            if (hdfsetStyle.Value == "2")
                            {
                                MinimumInventoryLevel = 0;
                                MaximumInventoryLevel = 0;
                                a = hdfsetStyle.Value.ToInt();
                            }

                            int ShowHomePage = ddlShowHomePage.SelectedValue.ToInt(0);


                            string kq = ProductController.Insert(cateID, 0, ProductTitle, ProductContent, ProductSKU, ProductStock, StockStatus, true, Regular_Price, CostOfGood, Retail_Price, "", 0, false, currentDate, username, supplierID, supplierName, txtMaterials.Text, MinimumInventoryLevel, MaximumInventoryLevel, a, ShowHomePage);

                            //Phần thêm ảnh đại diện sản phẩm
                            string path         = "/uploads/images/";
                            string ProductImage = "";
                            if (ProductThumbnailImage.UploadedFiles.Count > 0)
                            {
                                foreach (UploadedFile f in ProductThumbnailImage.UploadedFiles)
                                {
                                    var o = path + kq + '-' + convertToSlug(Path.GetFileName(f.FileName));
                                    try
                                    {
                                        f.SaveAs(Server.MapPath(o));
                                        ProductImage = o;
                                    }
                                    catch { }
                                }
                            }
                            string updateImage = ProductController.UpdateImage(kq.ToInt(), ProductImage);

                            //Phần thêm thư viện ảnh sản phẩm
                            string IMG = "";
                            if (hinhDaiDien.UploadedFiles.Count > 0)
                            {
                                foreach (UploadedFile f in hinhDaiDien.UploadedFiles)
                                {
                                    var o = path + kq + '-' + convertToSlug(Path.GetFileName(f.FileName));
                                    try
                                    {
                                        f.SaveAs(Server.MapPath(o));
                                        IMG = o;
                                        ProductImageController.Insert(kq.ToInt(), IMG, false, currentDate, username);
                                    }
                                    catch { }
                                }
                            }


                            if (kq.ToInt(0) > 0)
                            {
                                int ProductID = kq.ToInt(0);

                                string variable = hdfVariableListInsert.Value;
                                if (!string.IsNullOrEmpty(variable))
                                {
                                    string[] items = variable.Split(',');
                                    for (int i = 0; i < items.Length - 1; i++)
                                    {
                                        string   item        = items[i];
                                        string[] itemElement = item.Split(';');

                                        string   datanameid             = itemElement[0];
                                        string[] datavalueid            = itemElement[1].Split('|');
                                        string   datanametext           = itemElement[2];
                                        string   datavaluetext          = itemElement[3];
                                        string   productvariablesku     = itemElement[4].Trim().ToUpper();
                                        string   regularprice           = itemElement[5];
                                        string   costofgood             = itemElement[6];
                                        string   retailprice            = itemElement[7];
                                        string[] datanamevalue          = itemElement[8].Split('|');
                                        string   imageUpload            = itemElement[8];
                                        int      _MaximumInventoryLevel = itemElement[9].ToInt(0);
                                        int      _MinimumInventoryLevel = itemElement[10].ToInt(0);

                                        int stockstatus = itemElement[11].ToInt();

                                        HttpPostedFile postedFile = Request.Files["" + imageUpload + ""];
                                        string         image      = "";
                                        if (postedFile != null && postedFile.ContentLength > 0)
                                        {
                                            var o = path + kq + '-' + convertToSlug(Path.GetFileName(postedFile.FileName));
                                            postedFile.SaveAs(Server.MapPath(o));
                                            image = o;
                                        }

                                        string kq1 = ProductVariableController.Insert(ProductID, ProductSKU, productvariablesku, 0, stockstatus, Convert.ToDouble(regularprice),
                                                                                      Convert.ToDouble(costofgood), Convert.ToDouble(retailprice), image, true, false, currentDate, username,
                                                                                      supplierID, supplierName, _MinimumInventoryLevel, _MaximumInventoryLevel);

                                        string color             = "";
                                        string size              = "";
                                        int    ProductVariableID = 0;

                                        if (kq1.ToInt(0) > 0)
                                        {
                                            ProductVariableID = kq1.ToInt(0);
                                            color             = datavalueid[0];
                                            size = datavalueid[1];
                                            string[] Data      = datanametext.Split('|');
                                            string[] DataValue = datavaluetext.Split('|');
                                            for (int k = 0; k < Data.Length - 2; k++)
                                            {
                                                int    variablevalueID   = datavalueid[k].ToInt();
                                                string variableName      = Data[k];
                                                string variableValueName = DataValue[k];
                                                ProductVariableValueController.Insert(ProductVariableID, productvariablesku, variablevalueID,
                                                                                      variableName, variableValueName, false, currentDate, username);
                                            }
                                        }
                                        ProductVariableController.UpdateColorSize(ProductVariableID, color, size);
                                    }
                                }


                                PJUtils.ShowMessageBoxSwAlertCallFunction("Tạo sản phẩm thành công", "s", true, "redirectTo(" + kq + ")", Page);
                            }
                        }
                    }
                }
            }
        }
コード例 #34
0
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            //context.Response.Write("Hello World");
            string action      = context.Request["action"];
            string SourceTable = "";

            if (context.Request["SourceTable"] != null)
            {
                SourceTable = context.Request["SourceTable"];
            }
            Guid ToId = new Guid();

            if (context.Request["ToId"] != null && !string.IsNullOrEmpty(context.Request["ToId"]))
            {
                string tooid = context.Request["ToId"].ToString();
                ToId = Guid.Parse(context.Request["ToId"]);
            }
            string ShowName = "";

            if (context.Request["ShowName"] != null)
            {
                ShowName = context.Request["ShowName"];
            }
            string      JsonMsg = "";
            JsonMessage jmsg    = new JsonMessage();

            switch (action)
            {
            case "addImg":    //上传文件
                #region
                string         FileIdSet = "";
                List <File_tb> listFile  = new List <File_tb>();
                bool           IsValid   = true;//检查只能为图片,仅小于100k可以上传
                string         messge    = "";
                string[]       Types     = { ".jpg", ".jpeg", ".gif", ".bmp", ".png", ".ico" };
                int            lenth     = 1024 * 500;//一百k
                if (context.Request.Files.Count > 0)
                {
                    for (int i = 0; i < context.Request.Files.Count; i++)
                    {
                        HttpPostedFile hpFile = context.Request.Files[i];
                        if (!String.IsNullOrEmpty(hpFile.FileName))
                        {
                            string ext = System.IO.Path.GetExtension(hpFile.FileName);
                            if (!Types.Contains(ext.ToLower()))
                            {
                                IsValid = false;
                                messge  = "只能为图片类型";
                                break;
                            }
                            else if (hpFile.ContentLength > lenth)
                            {
                                IsValid = false;
                                messge  = "文件不能大于" + lenth / 1024 + "kB";
                                break;
                            }
                        }
                    }
                }
                if (context.Request.Files.Count > 0 && IsValid)
                {
                    for (int i = 0; i < context.Request.Files.Count; i++)
                    {
                        File_tb file = new File_tb();
                        file.Id = Guid.NewGuid();
                        if (context.Request["ToId"] == null)
                        {
                            file.ToId = file.Id;
                        }
                        else
                        {
                            file.ToId = ToId;
                        }
                        file.AddTime     = DateTime.Now;
                        file.UpdateTime  = DateTime.Now;
                        file.SourceTable = SourceTable;

                        file.ShowName = ShowName;
                        HttpPostedFile hpFile = context.Request.Files[i];
                        if (!String.IsNullOrEmpty(hpFile.FileName))
                        {
                            string ext = System.IO.Path.GetExtension(hpFile.FileName);
                            if (hpFile.ContentType != "image/jpeg" || hpFile.ContentType != "image/pjpeg")
                            {
                                file.FileType = "图片";
                                file.Suffix   = ext;
                                //给文件取随及名
                                Random ran = new Random();
                                file.FileName = hpFile.FileName.Substring(hpFile.FileName.LastIndexOf("\\") + 1);
                                if (String.IsNullOrEmpty(file.ShowName))
                                {
                                    file.ShowName = file.FileName;
                                }
                                int RandKey = ran.Next(100, 999);
                                file.FileName = DateTime.Now.ToString("yyyyMMddhhmmss") + "_" + RandKey + ext;
                                string fileName = file.FileName;
                                //保存文件
                                string path = context.Request.MapPath(fileName);

                                string uriString = System.Web.HttpContext.Current.Server.MapPath("~/Upload/").ToString();
                                file.Route     = "/Upload/";
                                file.FullRoute = "/Upload/" + path.Substring(path.LastIndexOf("\\") + 1);
                                hpFile.SaveAs(uriString + file.FullRoute.Substring(file.FullRoute.LastIndexOf("/") + 1));
                                //提示上传成功
                            }


                            /*添加一条信息;*/
                            object res = OPBiz.Add(file);
                            listFile.Add(file);
                            FileIdSet += file.FullRoute + ",";
                        }
                    }
                }
                if (IsValid)
                {
                    if (!String.IsNullOrEmpty(FileIdSet))
                    {
                        JsonMsg = JsonHelper.ToJson(new JsonMessage
                        {
                            Success = true,
                            Data    = JsonHelper.ToJson(listFile, true),
                            Message = "添加成功"
                        });
                    }
                    else
                    {
                        JsonMsg = JsonHelper.ToJson(new JsonMessage
                        {
                            Success = true,
                            Data    = "[]",
                            Message = "没有数据"
                        });
                    }
                }
                else
                {
                    JsonMsg = JsonHelper.ToJson(new JsonMessage
                    {
                        Success = false,
                        Data    = "[]",
                        Message = messge
                    });
                }

                context.Response.Write(JsonMsg);
                context.Response.End();

                #endregion
                break;

            case "addFile":    //上传文件
                #region
                string         FileIdSet2 = "";
                List <File_tb> listFile2  = new List <File_tb>();
                bool           IsValid2   = true;          //检查只能为图片,仅小于100k可以上传
                string         messge2    = "";
                int            lenth2     = 1024 * 200000; //一百k
                if (context.Request.Files.Count > 0)
                {
                    for (int i = 0; i < context.Request.Files.Count; i++)
                    {
                        HttpPostedFile hpFile = context.Request.Files[i];
                        if (!String.IsNullOrEmpty(hpFile.FileName))
                        {
                            string ext = System.IO.Path.GetExtension(hpFile.FileName);

                            if (hpFile.ContentLength > lenth2)
                            {
                                IsValid = false;
                                messge2 = "文件不能大于" + lenth2 / 1024 + "kB";
                                break;
                            }
                        }
                    }
                }
                if (context.Request.Files.Count > 0 && IsValid2)
                {
                    for (int i = 0; i < context.Request.Files.Count; i++)
                    {
                        File_tb file = new File_tb();
                        file.Id = Guid.NewGuid();
                        if (context.Request["ToId"] == null)
                        {
                            file.ToId = file.Id;
                        }
                        else
                        {
                            file.ToId = ToId;
                        }
                        file.AddTime     = DateTime.Now;
                        file.UpdateTime  = DateTime.Now;
                        file.SourceTable = SourceTable;

                        file.ShowName = ShowName;
                        HttpPostedFile hpFile = context.Request.Files[i];
                        if (!String.IsNullOrEmpty(hpFile.FileName))
                        {
                            string ext = System.IO.Path.GetExtension(hpFile.FileName);
                            if (hpFile.ContentType != "image/jpeg" || hpFile.ContentType != "image/pjpeg")
                            {
                                file.FileType = "文件";
                                file.Suffix   = ext;
                                //给文件取随及名
                                Random ran = new Random();
                                file.FileName = hpFile.FileName.Substring(hpFile.FileName.LastIndexOf("\\") + 1);
                                if (String.IsNullOrEmpty(file.ShowName))
                                {
                                    file.ShowName = file.FileName;
                                }
                                int RandKey = ran.Next(100, 999);
                                file.FileName = DateTime.Now.ToString("yyyyMMddhhmmss") + "_" + RandKey + ext;
                                string fileName = file.FileName;
                                //保存文件
                                string path = context.Request.MapPath(fileName);

                                string uriString = System.Web.HttpContext.Current.Server.MapPath("~/Upload/file/").ToString();
                                file.Route     = "/Upload/file/";
                                file.FullRoute = "/Upload/file/" + path.Substring(path.LastIndexOf("\\") + 1);
                                hpFile.SaveAs(uriString + file.FullRoute.Substring(file.FullRoute.LastIndexOf("/") + 1));
                                //提示上传成功
                            }


                            /*添加一条信息;*/
                            object res = OPBiz.Add(file);
                            listFile2.Add(file);
                            FileIdSet2 += file.FullRoute + ",";
                        }
                    }
                }
                if (IsValid2)
                {
                    if (!String.IsNullOrEmpty(FileIdSet2))
                    {
                        JsonMsg = JsonHelper.ToJson(new JsonMessage
                        {
                            Success = true,
                            Data    = JsonHelper.ToJson(listFile2, true),
                            Message = "添加成功"
                        });
                    }
                    else
                    {
                        JsonMsg = JsonHelper.ToJson(new JsonMessage
                        {
                            Success = true,
                            Data    = "[]",
                            Message = "没有数据"
                        });
                    }
                }
                else
                {
                    JsonMsg = JsonHelper.ToJson(new JsonMessage
                    {
                        Success = false,
                        Data    = "[]",
                        Message = messge2
                    });
                }

                context.Response.Write(JsonMsg);
                context.Response.End();

                #endregion
                break;

            case "GetFileList":    //根据id集获取文件列表

                #region
                string id = context.Request["ToId"];
                if (!string.IsNullOrEmpty(id))
                {
                    var            mql  = File_tbSet.SelectAll().Where(File_tbSet.ToId.Equal(id));
                    List <File_tb> list = OPBiz.GetOwnList(mql);
                    context.Response.Write(JsonHelper.ToJson(list, true));
                }
                else
                {
                    context.Response.Write("[]");
                }
                context.Response.End();
                #endregion
                break;

            case "SaveToid":    //保存更改ToID

                #region

                string Tid   = context.Request["ToId"];
                string IdSet = context.Request["IdSet"];
                if (!string.IsNullOrEmpty(context.Request["ToId"]) && !string.IsNullOrEmpty(context.Request["IdSet"]))
                {
                    string sql = " update File_tb set ToId='" + Tid + "'  where Id in (" + IdSet + ")";
                    int    i   = OPBiz.ExecuteSqlWithNonQuery(sql);
                    if (i > 0)
                    {
                        jmsg.Success = true;
                        jmsg.Data    = i.ToString();
                        jmsg.Message = "上传成功";
                    }
                    else
                    {
                        jmsg.Success = false;
                        jmsg.Data    = "0";
                        jmsg.Message = "上传失败";
                    }
                }
                else
                {
                    jmsg.Success = false;
                    jmsg.Data    = "0";
                    jmsg.Message = "数据为空";
                }
                context.Response.Write(JsonHelper.ToJson(jmsg, true));
                context.Response.End();

                #endregion
                break;

            case "Delfile":    //删除文件

                #region


                if (!string.IsNullOrEmpty(context.Request["IdSet"]))
                {
                    string sql = " delete from  File_tb   where Id in (" + context.Request["IdSet"] + ")";
                    int    i   = OPBiz.ExecuteSqlWithNonQuery(sql);
                    if (i > 0)
                    {
                        jmsg.Success = true;
                        jmsg.Data    = i.ToString();
                        jmsg.Message = "删除成功";
                    }
                    else
                    {
                        jmsg.Success = false;
                        jmsg.Data    = "0";
                        jmsg.Message = "删除失败";
                    }
                }
                else
                {
                    jmsg.Success = false;
                    jmsg.Data    = "0";
                    jmsg.Message = "数据为空";
                }
                context.Response.Write(JsonHelper.ToJson(jmsg, true));
                context.Response.End();

                #endregion
                break;

            case "Download":
                #region
                if (!string.IsNullOrEmpty(context.Request["Url"]))
                {
                    // 检查请求下载文件的有效性
                    string filePath = System.Web.HttpContext.Current.Server.MapPath(context.Request["Url"]);
                    if (!System.IO.File.Exists(filePath))
                    {
                        throw new ArgumentException("无效文件,文件不存在!");
                    }

                    //WriteFile实现下载
                    string   fileName = context.Request["fileName"];  //客户端保存的文件名
                    FileInfo fileInfo = new FileInfo(filePath);
                    context.Response.Clear();
                    context.Response.ClearContent();
                    context.Response.ClearHeaders();
                    context.Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
                    context.Response.AddHeader("Content-Length", fileInfo.Length.ToString());
                    context.Response.AddHeader("Content-Transfer-Encoding", "binary");
                    context.Response.ContentType     = "application/octet-stream";
                    context.Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
                    context.Response.WriteFile(fileInfo.FullName);
                    context.Response.Flush();
                    context.Response.End();
                }
                #endregion

                break;
            }
        }
コード例 #35
0
        //public static bool GetImportedDataTable(HttpPostedFile fileUploaded, string uploadFolder, out string message,
        //                                            out DataTable dt)
        //{
        //    return GetImportedDataTable(fileUploaded, uploadFolder, out message, out dt, new Hashtable());
        //}

        public static bool GetImportedDataTable(HttpPostedFile fileUploaded, string uploadFolder, out string message,
                                                out DataTable dt, Hashtable param, string configFileName)
        {
            dt = new DataTable();
            if (fileUploaded == null || string.IsNullOrEmpty(fileUploaded.FileName))
            {
                message = "请选择上传文件";
                return(false);
            }

            const int maxLength = 1024 * 1024 * 8; //最大4M,否则内存占用太严重,需要让用户自己拆分文件

            if (fileUploaded.ContentLength <= 0 || fileUploaded.ContentLength > maxLength)
            {
                message = "上传文件大小应在8M内";
                return(false);
            }

            string mime = fileUploaded.ContentType;

            //text/csv
            if (!mime.Equals("text/csv", StringComparison.InvariantCultureIgnoreCase) &&
                !mime.Equals("application/vnd.ms-excel", StringComparison.InvariantCultureIgnoreCase) &&
                !fileUploaded.FileName.EndsWith(".csv", StringComparison.InvariantCultureIgnoreCase))
            {
                message = string.Format("上传文件的格式'{0}'无法识别, 或者文件正在被使用.", mime);
                return(false);
            }

            string filename = fileUploaded.FileName;

            filename = filename.Substring(filename.LastIndexOf('\\') + 1);


            //将上传的文件保存到服务器磁盘
            string tempFileName = Path.Combine(uploadFolder, "temp_" + DateTime.Now.ToFileTime() + filename);

            fileUploaded.SaveAs(tempFileName);
            bool result = false;

            try
            {
                //return new ExcelHelper().ImportExcelData(tempFileName, "", out dt, out message, param);
                result = ImportExcelData(tempFileName, "", out dt, out message, param);
            }
            catch (InvalidDataException)
            {
                dt      = null;
                message = "ERROR";
                result  = false;
            }

            if (result)
            {
                if (File.Exists(configFileName))
                {
                    string qualifyResult = EnsureDataTableQualify(dt, configFileName, param);
                    if (!string.IsNullOrEmpty(qualifyResult))
                    {
                        message += qualifyResult;
                        result   = false;
                    }
                }
            }
            File.Delete(tempFileName);
            return(result);
        }
コード例 #36
0
ファイル: Images.cs プロジェクト: changtraicantinh/atpgroup
    public static string UploadImageToServer(string MapPath, HttpPostedFile Input, string FileExtension, string SavingFolder)
    {
        string sUploadImageFolder = SavingFolder;
        string sCurrentDatetime = "";
        string sFolder = "";
        string sFileName = "";
        string sFilePath = "";
        sCurrentDatetime = DateTime.Now.Ticks.ToString();
        sFolder = MapPath;

        //sFileName = Input.FileName;// ConvertFileName(Input.FileName);
        sFileName = sCurrentDatetime + FileExtension;

        sFolder = MapPath;
        sFolder = sFolder + sUploadImageFolder;

        if (!Directory.Exists(sFolder))
        {
            Directory.CreateDirectory(sFolder);
        }
        sFilePath = sFolder + sFileName;
        try {
            Input.SaveAs(sFilePath);
        }
        catch {
            sFilePath = sFolder + sFileName;
            Input.SaveAs(sFilePath);
        }

        return sFileName;
    }
コード例 #37
0
        public IHttpActionResult UploadTemplate(string projectid)
        {
            HttpRequest        request      = System.Web.HttpContext.Current.Request;
            HttpFileCollection FileCollect  = request.Files;
            string             resultStr    = string.Empty;
            string             internalName = string.Empty;

            ClosureConsInvtChecking woEntity = null;
            bool isNew = false;

            if (FileCollect.Count > 0) //如果集合的数量大于0
            {
                //用key获取单个文件对象HttpPostedFile
                HttpPostedFile fileSave      = FileCollect[0];
                string         fileName      = Path.GetFileName(fileSave.FileName);
                string         fileExtension = Path.GetExtension(fileSave.FileName);
                var            current       = System.Web.HttpContext.Current;

                internalName = Guid.NewGuid() + fileExtension;
                string filePath = current.Server.MapPath("~/") + "UploadFiles\\" + internalName;
                //通过此对象获取文件名

                fileSave.SaveAs(filePath);

                string column = "E";
                woEntity = ClosureConsInvtChecking.Get(projectid);

                var fileInfo = new FileInfo(filePath);
                //验证上传EXCEL版本
                var vn = ExcelHelper.GetExcelVersionNumber(filePath);
                if (vn != ConsInvtCheckingVersion)
                {
                    PluploadHandler.WriteErrorMsg("上传附件版本号不一致");
                }

                var importDirector = new ExcelDataImportDirector(fileInfo, ExcelDataImportType.ClosureWOCheckList);

                if (woEntity == null)
                {
                    isNew                      = true;
                    woEntity                   = new ClosureConsInvtChecking();
                    woEntity.ProjectId         = projectid;
                    woEntity.Id                = Guid.NewGuid();
                    woEntity.CreateTime        = DateTime.Now;
                    woEntity.CreateUserAccount = ClientCookie.UserCode;

                    woEntity.IsHistory = false;
                }

                woEntity.TotalOriginalBudget = GetDecimalValue(importDirector, 16, column);
                woEntity.TotalNBVBudget      = GetDecimalValue(importDirector, 17, column);
                woEntity.TotalWriteoffBudget = GetDecimalValue(importDirector, 18, column);
                var woCheckList = ClosureWOCheckList.Get(projectid);
                if (woCheckList != null)
                {
                    if (!EqualValue(woCheckList.TotalCost_Original, woEntity.TotalOriginalBudget))
                    {
                        PluploadHandler.WriteErrorMsg("Total Budget 数据验证不通过,请检查后重试!");
                    }

                    if (!EqualValue(woCheckList.TotalCost_NBV, woEntity.TotalNBVBudget))
                    {
                        PluploadHandler.WriteErrorMsg("Total NBV(Closure Data) 数据验证不通过,请检查后重试!");
                    }

                    if (!EqualValue(woCheckList.TotalCost_WriteOFF, woEntity.TotalWriteoffBudget))
                    {
                        PluploadHandler.WriteErrorMsg("Total Write off 数据验证不通过,请检查后重试!");
                    }
                }
                woEntity.RECostBudget      = GetDecimalValue(importDirector, 19, column);
                woEntity.LHIBudget         = GetDecimalValue(importDirector, 20, column);
                woEntity.ESSDBudget        = GetDecimalValue(importDirector, 21, column);
                woEntity.EquipmentBudget   = GetDecimalValue(importDirector, 22, column);
                woEntity.SignageBudget     = GetDecimalValue(importDirector, 23, column);
                woEntity.SeatingBudget     = GetDecimalValue(importDirector, 24, column);
                woEntity.DecorationBudget  = GetDecimalValue(importDirector, 25, column);
                woEntity.ClosingCostBudegt = GetDecimalValue(importDirector, 26, column);

                woEntity.ClosingCostActual = GetDecimalValue(importDirector, 27, column);
                woEntity.TotalActual       = GetDecimalValue(importDirector, 28, column);

                woEntity.RECostActual     = GetDecimalValue(importDirector, 29, column);
                woEntity.LHIActual        = GetDecimalValue(importDirector, 30, column);
                woEntity.EquipmentActual  = GetDecimalValue(importDirector, 31, column);
                woEntity.SignageActual    = GetDecimalValue(importDirector, 32, column);
                woEntity.SeatingActual    = GetDecimalValue(importDirector, 33, column);
                woEntity.DecorationActual = GetDecimalValue(importDirector, 34, column);
                woEntity.RECostVsBudget   = GetDecimalValue(importDirector, 35, column);
                woEntity.LHIWOVsBudget    = GetDecimalValue(importDirector, 36, column);

                woEntity.ESSDWOVsBudget   = GetDecimalValue(importDirector, 37, column);
                woEntity.TTLWOVsBudget    = GetDecimalValue(importDirector, 38, column);
                woEntity.REExplanation    = GetStringValue(importDirector, 39, column);
                woEntity.LHIExplanation   = GetStringValue(importDirector, 40, column);
                woEntity.ESSDExplanation  = GetStringValue(importDirector, 41, column);
                woEntity.TotalExplanation = GetStringValue(importDirector, 42, column);


                Attachment att = Attachment.GetAttachment("ClosureConsInvtChecking", woEntity.Id.ToString(), "Template");
                if (att == null)
                {
                    att              = new Attachment();
                    att.ID           = Guid.NewGuid();
                    att.TypeCode     = "Template";
                    att.RefTableName = ClosureConsInvtChecking.TableName;
                    att.RefTableID   = woEntity.Id.ToString();
                    att.RelativePath = "//";
                }
                att.InternalName    = internalName;
                att.Name            = fileName;
                att.Extension       = fileExtension;
                att.Length          = FileCollect[0].ContentLength;
                att.CreateTime      = DateTime.Now;
                att.CreatorID       = ClientCookie.UserCode;
                att.CreatorNameENUS = ClientCookie.UserNameENUS;
                att.CreatorNameZHCN = ClientCookie.UserNameZHCN;
                Attachment.SaveSigleFile(att);

                var currentNode = NodeInfo.GetCurrentNode(projectid, FlowCode.Closure_ConsInvtChecking);
                var newNode     = NodeInfo.GetNodeInfo(NodeCode.Closure_ConsInvtChecking_ResultUpload);
                if (newNode.Sequence > currentNode.Sequence)
                {
                    ProjectInfo.FinishNode(projectid, FlowCode.Closure_ConsInvtChecking, NodeCode.Closure_ConsInvtChecking_DownLoadTemplate);
                    ProjectInfo.FinishNode(projectid, FlowCode.Closure_ConsInvtChecking, NodeCode.Closure_ConsInvtChecking_WriteOffData);
                    ProjectInfo.FinishNode(projectid, FlowCode.Closure_ConsInvtChecking, NodeCode.Closure_ConsInvtChecking_ResultUpload);
                }

                if (isNew)
                {
                    ClosureConsInvtChecking.Add(woEntity);
                }
                else
                {
                    ClosureConsInvtChecking.Update(woEntity);
                }
            }
            return(Ok(woEntity));
        }
コード例 #38
0
 /// <summary>
 /// 上传文件并返回文件的相对路径
 /// </summary>
 /// <param name="hpFile">上传文件</param>
 /// <param name="companySavePath">公司保存路径</param>
 /// <returns></returns>
 public static string SaveUploadPhoto(HttpPostedFile hpFile, string companySavePath)
 {
     //上传后的文件名
     string newFileName = "";
     //获取文件名
     string oldFilePath = hpFile.FileName;
     //上传路径输入时
     if (!string.IsNullOrEmpty(oldFilePath))
     {
         //取得上传文件的扩展名
         string extension = oldFilePath.Substring(oldFilePath.LastIndexOf(".")).ToLower();
         //不允许上传的文件格式时
         if (StringUtil.GetInArrayID(extension, ConstUtil.SAVE_PHOTO_TYPE) < 0)
         {
             return null;
         }
         //文件上传后的命名
         newFileName = HtmlInputFileControl.GetUniqueString() + extension;
         //文件路径是否存在
         DirectoryInfo folder = new DirectoryInfo(companySavePath);
         //目录不存在,则创建新的目录
         if (!folder.Exists)
         {
             //创建目录
             folder.Create();
         }
         //保存文件
         hpFile.SaveAs(companySavePath + "/" + newFileName);
     }
     else
         return null;
     //返回新的文件路径
     //return companySavePath + "/" + newFileName;
     return companyCD + "/" + newFileName;
 }
コード例 #39
0
        private void importroomsource(HttpContext context)
        {
            HttpFileCollection uploadFiles = context.Request.Files;

            if (uploadFiles.Count == 0)
            {
                context.Response.Write("请选择一个文件");
                return;
            }
            if (string.IsNullOrEmpty(uploadFiles[0].FileName))
            {
                context.Response.Write("请选择一个文件");
                return;
            }
            HttpPostedFile postedFile = uploadFiles[0];
            string         filepath   = HttpContext.Current.Server.MapPath("~/upload/ImportRoomSource/" + DateTime.Now.ToString("yyyyMMdd"));

            if (!System.IO.Directory.Exists(filepath))
            {
                System.IO.Directory.CreateDirectory(filepath);
            }
            string filename = DateTime.Now.ToLocalTime().ToString("yyyyMMddHHmmss") + "_" + postedFile.FileName;
            string fullpath = Path.Combine(filepath, filename);

            postedFile.SaveAs(fullpath);
            string    msg   = string.Empty;
            DataTable table = ExcelExportHelper.NPOIReadExcel(fullpath);

            if (!table.Columns.Contains("资源ID"))
            {
                msg += "<p>导入失败,原因:资源ID列不存在</p>";
                WebUtil.WriteJson(context, msg);
                return;
            }
            int MinID = table.Select().Min(r =>
            {
                int ID = 0;
                if (r.Field <object>("资源ID") != null)
                {
                    int.TryParse(r.Field <object>("资源ID").ToString(), out ID);
                }
                return(ID);
            });
            int MaxID = table.Select().Max(r =>
            {
                int ID = 0;
                if (r.Field <object>("资源ID") != null)
                {
                    int.TryParse(r.Field <object>("资源ID").ToString(), out ID);
                }
                return(ID);
            });
            string TableName          = Utility.EnumModel.DefineFieldTableName.RoomBasic.ToString();
            string TableName_Relation = Utility.EnumModel.DefineFieldTableName.RoomPhoneRelation.ToString();
            string isconver           = context.Request["isconver"];
            bool   ImportFailed       = false;
            int    count       = 0;
            var    comm_helper = new APPCode.CommHelper();

            titleList = GetTableColumns();
            var basicList = RoomBasic.GetRoomBasicListByMinMaxRoomID(MinID, MaxID);
            var phoneList = RoomPhoneRelation.GetRoomPhoneRelationListByMinMaxRoomID(MinID, MaxID);

            using (SqlHelper helper = new SqlHelper())
            {
                try
                {
                    helper.BeginTransaction();
                    #region 导入处理
                    for (int i = 0; i < table.Rows.Count; i++)
                    {
                        count = i;
                        Project project = null;
                        object  Value   = table.Rows[i]["资源ID"];
                        int     RoomID  = 0;
                        if (Value != null)
                        {
                            int.TryParse(Value.ToString(), out RoomID);
                        }
                        if (RoomID > 0)
                        {
                            project = Foresight.DataAccess.Project.GetProject(RoomID, helper);
                        }
                        if (project == null)
                        {
                            msg         += "<p>第" + (i + 2) + "行上传失败。原因:所属项目不存在</p>";
                            ImportFailed = true;
                            break;
                        }
                        if (GetColumnValue("房号", table, i, out Value))
                        {
                            project.Name = Value.ToString().Trim();
                        }
                        project.Save(helper);
                        RoomBasic basic = basicList.FirstOrDefault(p => p.RoomID == project.ID);
                        if (isconver.Equals("0") && basic != null)
                        {
                            continue;
                        }
                        if (basic == null)
                        {
                            basic         = new RoomBasic();
                            basic.RoomID  = project.ID;
                            basic.AddTime = DateTime.Now;
                        }
                        if (GetColumnValue("期数", table, i, out Value))
                        {
                            basic.BuildingNumber = Value.ToString().Trim();
                        }
                        if (GetColumnValue("签约日期", table, i, out Value))
                        {
                            basic.SignDate = GetDateTimeValue(Value);
                        }
                        if (GetColumnValue("交付时间", table, i, out Value))
                        {
                            basic.PaymentTime = GetDateTimeValue(Value);
                        }
                        if (GetColumnValue("产权办理时间", table, i, out Value))
                        {
                            basic.CertificateTime = GetDateTimeValue(Value);
                        }
                        if (GetColumnValue("房产类别", table, i, out Value))
                        {
                            basic.RoomType = Value.ToString().Trim();
                        }
                        if (GetColumnValue("精装修情况", table, i, out Value))
                        {
                            basic.IsJingZhuangXiu = 0;
                            if (Value.ToString().Trim().Equals("是"))
                            {
                                basic.IsJingZhuangXiu = 1;
                            }
                            if (Value.ToString().Trim().Equals("否"))
                            {
                                basic.IsJingZhuangXiu = 2;
                            }
                        }
                        if (GetColumnValue("建筑面积", table, i, out Value))
                        {
                            basic.BuildingOutArea = GetDecimalValue(Value);
                        }
                        List <RoomPhoneRelation> roomPhoneRelationList = new List <RoomPhoneRelation>();
                        string phoneName = string.Empty;
                        if (GetColumnValue("业主1", table, i, out Value))
                        {
                            phoneName = Value.ToString().Trim();
                        }
                        if (!string.IsNullOrEmpty(phoneName))
                        {
                            var myPhoneRelation = phoneList.FirstOrDefault(p => p.RoomID == basic.RoomID && p.RelationName.Equals(phoneName));
                            if (myPhoneRelation == null)
                            {
                                myPhoneRelation         = new RoomPhoneRelation();
                                myPhoneRelation.AddTime = DateTime.Now;
                                myPhoneRelation.RoomID  = basic.RoomID;
                            }
                            myPhoneRelation.RelationType = "homefamily";
                            myPhoneRelation.RelationName = phoneName;
                            if (GetColumnValue("业主1联系方式", table, i, out Value))
                            {
                                myPhoneRelation.RelatePhoneNumber = Value.ToString().Trim();
                            }
                            myPhoneRelation.Save(helper);
                        }
                        phoneName = string.Empty;
                        if (GetColumnValue("业主2", table, i, out Value))
                        {
                            phoneName = Value.ToString().Trim();
                        }
                        if (!string.IsNullOrEmpty(phoneName))
                        {
                            var myPhoneRelation = phoneList.FirstOrDefault(p => p.RoomID == basic.RoomID && p.RelationName.Equals(phoneName));
                            if (myPhoneRelation == null)
                            {
                                myPhoneRelation         = new RoomPhoneRelation();
                                myPhoneRelation.AddTime = DateTime.Now;
                                myPhoneRelation.RoomID  = basic.RoomID;
                            }
                            myPhoneRelation.RelationType = "homefamily";
                            myPhoneRelation.RelationName = phoneName;
                            if (GetColumnValue("业主2联系方式", table, i, out Value))
                            {
                                myPhoneRelation.RelatePhoneNumber = Value.ToString().Trim();
                            }
                            myPhoneRelation.Save(helper);
                        }
                        phoneName = string.Empty;
                        if (GetColumnValue("住户1", table, i, out Value))
                        {
                            phoneName = Value.ToString().Trim();
                        }
                        if (!string.IsNullOrEmpty(phoneName))
                        {
                            var myPhoneRelation = phoneList.FirstOrDefault(p => p.RoomID == basic.RoomID && p.RelationName.Equals(phoneName));
                            if (myPhoneRelation == null)
                            {
                                myPhoneRelation         = new RoomPhoneRelation();
                                myPhoneRelation.AddTime = DateTime.Now;
                                myPhoneRelation.RoomID  = basic.RoomID;
                            }
                            myPhoneRelation.RelationType = "rentfamily";
                            myPhoneRelation.RelationName = phoneName;
                            if (GetColumnValue("住户1联系方式", table, i, out Value))
                            {
                                myPhoneRelation.RelatePhoneNumber = Value.ToString().Trim();
                            }
                            myPhoneRelation.Save(helper);
                        }
                        basic.Save(helper);
                    }
                    #endregion
                    if (!ImportFailed)
                    {
                        helper.Commit();
                        msg += "<p>导入完成</p>";
                    }
                    else
                    {
                        helper.Rollback();
                        msg += "<p>导入失败</p>";
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.WriteError("ImportSourceHandler", "visit: importroomsource", ex);
                    msg = "第" + (count + 2) + "行数据有问题,导入取消";
                    helper.Rollback();
                }
                context.Response.Write(msg);
            }
        }
コード例 #40
0
ファイル: upload.aspx.cs プロジェクト: rongcheng/benz
    private void uploadSourceFile(HttpPostedFile hpf) {
        string filename = hpf.FileName;
        string fileType = Path.GetExtension(filename);
        string savePath = string.Empty;
        //yangguang
        //if (fileType.IndexOf(".") > -1)
        //{
        //    savePath = ResourceTypeFactory.getResourceType(fileType.Substring(1)).SourcePath;
        //}
        //else
        //{
        //    savePath = ResourceTypeFactory.getResourceType(fileType).SourcePath;
        //}
        if (fileType.IndexOf(".") > -1) {
            savePath = ResourceTypeFactory.getResourceType(fileType.Substring(1)).GetSourcePath();
        }
        else {
            savePath = ResourceTypeFactory.getResourceType(fileType).GetSourcePath();
        }
        
        savePath = Path.Combine(savePath, CurrentUser.UserLoginName);


        string resourceseq = Path.GetFileNameWithoutExtension(savedFileName);
        string fileFullPath = Path.Combine(savePath, resourceseq + fileType);

        try {
            if (!Directory.Exists(savePath)) {
                Directory.CreateDirectory(savePath);
            }
            //Console.WriteLine("Pre   Content Length-----" + hpf.ContentLength);
            //Console.WriteLine("Pre Current-----" + hpf.InputStream.Seek(0, SeekOrigin.Current));
            //Console.WriteLine("Pre  position-----" + hpf.InputStream.Position);
            //Console.WriteLine("Pre  Length-----" + hpf.InputStream.Length);
            hpf.SaveAs(fileFullPath);
            //Console.WriteLine("Re Content Length-----" + hpf.ContentLength);
            //Console.WriteLine("Re Current-----" + hpf.InputStream.Seek(0, SeekOrigin.Current));
            //Console.WriteLine("Re  Position -----" + hpf.InputStream.Position);
            //Console.WriteLine("Re Length-----" + hpf.InputStream.Length);

            //Console.WriteLine("End -----" + hpf.InputStream.Seek(0, SeekOrigin.End));
            //Console.WriteLine("End  postion-----" + hpf.InputStream.Position);
        }
        catch (Exception ep) {
            LogWriter.WriteExceptionLog(ep, true);
        }
    }
コード例 #41
0
 private void UploadVideo(string virtualFolder, HttpPostedFile file, string fileName)
 {
     try
     {
         var folder = HttpContext.Current.Server.MapPath(virtualFolder);
         if (!Directory.Exists(folder))
         {
             Directory.CreateDirectory(folder);
         }
         file.SaveAs(folder + fileName);
     }
     catch (Exception exception)
     {
         RDN.Library.Classes.Error.ErrorDatabaseManager.AddException(exception, exception.GetType());
     }
 }
コード例 #42
0
ファイル: DALCRelatedFile.cs プロジェクト: elieli/nonProfit
    /// <summary>
    ///		Обновляет информацию о связанном файле
    /// </summary>
    public static int Update(int id, int productID, string name, string description, HttpPostedFile pf, string fileName, string special, int order)
    {
        string fileExtension = "";
            string originalFileName = "";
            string newFileName = fileName;
            string fileFullName;
            FileInfo fileInfo;

            if (pf != null)
            {
                DeleteFile(id);

                int cnt = -1;

                FileInfo wFile = new FileInfo(pf.FileName);
                originalFileName = wFile.Name;
                fileExtension = wFile.Extension;
                fileExtension = fileExtension.StartsWith(".") ? fileExtension.Remove(0, 1) : fileExtension;

                do
                {
                    cnt++;
                    newFileName = fileName + ((cnt==0)?"":"_"+cnt.ToString());

                    fileExtension = fileExtension.StartsWith(".") ? fileExtension.Remove(0, 1) : fileExtension;

                    fileFullName = GetFileName((productID>=0?"":"temp/") + newFileName, fileExtension);

                    fileInfo = new FileInfo(fileFullName);
                } while(fileInfo.Exists);

                pf.SaveAs(fileFullName);
            }

            int returnValue = 0;
            SqlParameter[] arParams = new SqlParameter[9];

            arParams[0] = new SqlParameter("@rlflID", id);
            arParams[1] = new SqlParameter("@rlfl_ProductID", productID <= 0?
                DBNull.Value : (object)productID);
            arParams[2] = new SqlParameter("@rlflName", name);
            arParams[3] = new SqlParameter("@rlflDescription", description);
            arParams[4] = new SqlParameter("@rlflFileName", newFileName);
            arParams[5] = new SqlParameter("@rlflFileExtension", fileExtension);
            arParams[6] = new SqlParameter("@rlflOriginalFileName", originalFileName);
            arParams[7] = new SqlParameter("@rlflSpecial", special);
            arParams[8] = new SqlParameter("@rlflOrder", order);

            returnValue = Convert.ToInt32( SqlHelper.ExecuteScalar(m_sConnectionString, "ecom_RelatedFile_Update", arParams) );

            return returnValue;
    }
コード例 #43
0
ファイル: ApiService.cs プロジェクト: brandaorafael/Trillo
    public bool FileUpload(string caminho, string nomeBaseArquivo, HttpPostedFile arquivo)
    {
        if (arquivo.ContentLength > 10485760) return false;
        try
        {
            //Cria a pasta do cliente caso não exista
            if (!Directory.Exists(caminho))
                Directory.CreateDirectory(caminho);

            arquivo.SaveAs(caminho + nomeBaseArquivo + Path.GetExtension(arquivo.FileName));
            return true;
        }
        catch (Exception)
        {
            return false;
        }
    }
コード例 #44
0
ファイル: Uploader.cs プロジェクト: BlogPark/BBSWebProject
    /**
      * 上传文件的主处理方法
      * @param HttpContext
      * @param string
      * @param  string[]
      *@param int
      * @return Hashtable
      */
    public Hashtable upFile(HttpContext cxt, string pathbase, string[] filetype, int size)
    {
        var account = 1;
        //pathbase = pathbase + DateTime.Now.ToString("yyyyMMdd")+ "/";//������վ�µ�·��
        pathbase = (pathbase + 1.ToString() + "/").TrimStart('/');//������վ�µ�·��
        string upload_picture_path = System.Configuration.ConfigurationManager.AppSettings["UPLOAD_PICTURE_PATH"];//�����ļ������õ��ļ��ϴ���ַ
        //uploadpath = cxt.Server.MapPath(pathbase);//获取文件上传路径//ϵͳԭ���Ĵ���ļ�λ��
        uploadpath = (upload_picture_path + pathbase.Replace("/", "\\")).Replace("\\", @"\");//��װ��ľ�����λ��
        //CreateFolder(DateTime.Now)
        try
        {
            uploadFile = cxt.Request.Files[0];
            originalName = uploadFile.FileName;

            //目录创建
            createFolder();

            //格式验证
            if (checkType(filetype))
            {
                //不允许的文件类型
                state = "\u4e0d\u5141\u8bb8\u7684\u6587\u4ef6\u7c7b\u578b";
            }
            //大小验证
            if (checkSize(size))
            {
                //文件大小超出网站限制
                state = "\u6587\u4ef6\u5927\u5c0f\u8d85\u51fa\u7f51\u7ad9\u9650\u5236";
            }
            //保存图片
            if (state == "SUCCESS")
            {
                filename = reName();
                uploadFile.SaveAs(uploadpath + filename);
                URL =webstr+ pathbase + filename;
            }
        }
        catch (Exception e)
        {
            // 未知错误
            state = "\u672a\u77e5\u9519\u8bef";
            URL = "";
        }
        return getUploadInfo();
    }
コード例 #45
0
        protected void btnAddPhoto_Click(object sender, EventArgs e)
        {
            int    result = 0;
            string ext    = null;;

            byte[] t_Image  = null;
            Double FileSize = 0;

            if ((ddlAlbum.SelectedValue == "0") || (ddlSubalbum.SelectedValue == "0" || ddlSubalbum.SelectedValue == "") || (txtPhoto.Text == "") || (!PhotoUpload.HasFile))
            {
                ScriptManager.RegisterStartupScript(this, typeof(Page), "msg", "alert('All fields are mandatory!');", true);
                return;
            }
            if (CheckValidPhoto() < 1)
            {
                return;
            }

            HttpFileCollection fileCollection = Request.Files;

            if (PhotoUpload.HasFile)
            {
                if (isValidAttachmentFile(PhotoUpload))
                {
                    ext      = System.IO.Path.GetExtension(PhotoUpload.FileName);
                    t_Image  = PhotoUpload.FileBytes;
                    FileSize = PhotoUpload.PostedFile.ContentLength / 1024;
                }
                else
                {
                    ScriptManager.RegisterStartupScript(this, typeof(Page), "msg", "alert('File Invalid');", true);;
                    return;
                }


                FileInfo file        = new FileInfo(PhotoUpload.FileName);
                Bitmap   img         = new Bitmap(PhotoUpload.FileContent);
                var      imageHeight = img.Height;
                var      imageWidth  = img.Width;
                if (imageHeight != 420 && imageWidth != 640)
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('Photograph should fall between 420 to 640 pixels.')", true);
                    return;
                }
            }

            for (int i = 0; i < fileCollection.Count; i++)
            {
                HttpPostedFile uploadfile1 = fileCollection[i];
                string         fileNames   = Path.GetFileName(uploadfile1.FileName);
                if (CommonFuntion.check_Extensions(fileNames) == true)
                {
                    if (uploadfile1.ContentLength > 0)
                    {
                        ext = fileNames.ToString();
                        String     extention = ext.Substring(ext.IndexOf(".") + 1, 3);
                        SqlCommand t_SQLCmd  = new SqlCommand();
                        String     strSQL    = string.Empty;
                        string     filename  = string.Empty;

                        filename = fileNames;
                        filename = filename.Substring(0, filename.IndexOf('.')) + "_" + System.DateTime.Now.ToString().Replace("/", "_") + System.IO.Path.GetExtension(fileNames);
                        filename = filename.Replace(":", "_");
                        uploadfile1.SaveAs(Server.MapPath("../../App/PhotoAlbum/" + fileNames));    //  fileCollection[i]));
                        objAlbumSchema.Actiontype      = "Insert";
                        objAlbumSchema.Name            = txtPhoto.Text.ToString();
                        objAlbumSchema.PhotoSubAlbumID = Convert.ToInt32(ddlSubalbum.SelectedValue);
                        objAlbumSchema.Filename        = fileNames;
                        int isinsert = objAlbumBL.DMLAlbumDetails(objAlbumSchema);
                        BindPhoto();
                    }
                }
            }
            if (result == 1)
            {
                ScriptManager.RegisterStartupScript(this, typeof(Page), "msg", "alert('Save SucessFully');", true);
            }
        }
コード例 #46
0
        public void ProcessRequest(HttpContext context)
        {
            String aspxUrl = context.Request.Path.Substring(0, context.Request.Path.LastIndexOf("/") + 1);

            //文件保存目录路径
            String savePath = "/attached/";

            //文件保存目录URL
            String saveUrl = aspxUrl + "/attached/";

            //定义允许上传的文件扩展名
            Hashtable extTable = new Hashtable();

            extTable.Add("image", "gif,jpg,jpeg,png,bmp");
            extTable.Add("flash", "swf,flv");
            extTable.Add("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
            extTable.Add("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");

            //最大文件大小
            int maxSize = 1000000;

            this.context = context;

            HttpPostedFile imgFile = context.Request.Files["imgFile"];

            if (imgFile == null)
            {
                showError("请选择文件。");
            }

            String dirPath = context.Server.MapPath(savePath);

            if (!Directory.Exists(dirPath))
            {
                showError("上传目录不存在。");
            }

            String dirName = context.Request.QueryString["dir"];

            if (String.IsNullOrEmpty(dirName))
            {
                dirName = "image";
            }
            if (!extTable.ContainsKey(dirName))
            {
                showError("目录名不正确。");
            }

            String fileName = imgFile.FileName;
            String fileExt  = Path.GetExtension(fileName).ToLower();

            if (imgFile.InputStream == null || imgFile.InputStream.Length > maxSize)
            {
                showError("上传文件大小超过限制。");
            }

            if (String.IsNullOrEmpty(fileExt) || Array.IndexOf(((String)extTable[dirName]).Split(','), fileExt.Substring(1).ToLower()) == -1)
            {
                showError("上传文件扩展名是不允许的扩展名。\n只允许" + ((String)extTable[dirName]) + "格式。");
            }

            //创建文件夹
            dirPath += dirName + "/";
            saveUrl += dirName + "/";
            if (!Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath);
            }
            String ymd = DateTime.Now.ToString("yyyyMMdd", DateTimeFormatInfo.InvariantInfo);

            dirPath += ymd + "/";
            saveUrl += ymd + "/";
            if (!Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath);
            }

            String newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + fileExt;
            String filePath    = dirPath + newFileName;

            imgFile.SaveAs(filePath);

            String fileUrl = saveUrl + newFileName;

            Hashtable hash = new Hashtable();

            hash["error"] = 0;
            hash["url"]   = fileUrl;
            context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8");
            context.Response.Write(JsonMapper.ToJson(hash));
            context.Response.End();
        }
コード例 #47
0
        protected void btnCadastrar_Click(object sender, EventArgs e)
        {
            con.Open();

            if (FileUploadControl.PostedFile.ContentLength < 8388608)
            {
                try
                {
                    if (FileUploadControl.HasFile)
                    {
                        try
                        {
                            //Aqui ele vai filtrar pelo tipo de arquivo
                            if (FileUploadControl.PostedFile.ContentType == "image/jpeg" ||
                                FileUploadControl.PostedFile.ContentType == "image/png" ||
                                FileUploadControl.PostedFile.ContentType == "image/gif" ||
                                FileUploadControl.PostedFile.ContentType == "image/bmp")
                            {
                                try
                                {
                                    //Obtem o  HttpFileCollection
                                    HttpFileCollection hfc = Request.Files;
                                    for (int i = 0; i < hfc.Count; i++)
                                    {
                                        HttpPostedFile hpf = hfc[i];
                                        if (hpf.ContentLength > 0)
                                        {
                                            //Pega o nome do arquivo
                                            nome = System.IO.Path.GetFileName(hpf.FileName);
                                            //Pega a extensão do arquivo
                                            extensao = System.IO.Path.GetExtension(hpf.FileName);
                                            //Gera nome novo do Arquivo numericamente
                                            filename = string.Format("{0:00000000000000}", GerarID());
                                            //Caminho a onde será salvo
                                            hpf.SaveAs(Server.MapPath("~/uploads/fotos/") + filename + i + extensao);

                                            //Prefixo p/ img pequena
                                            var prefixoP = "-p";
                                            //Prefixo p/ img grande
                                            var prefixoG = "-g";

                                            //pega o arquivo já carregado
                                            pth = Server.MapPath("~/uploads/fotos/") + filename + i + extensao;

                                            //Redefine altura e largura da imagem e Salva o arquivo + prefixo

                                            Redefinir.resizeImageAndSave(pth, 70, 53, prefixoP);
                                            Redefinir.resizeImageAndSave(pth, 500, 331, prefixoG);
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    StatusLabel.Text = ex.Message;
                                }
                                // Mensagem se tudo ocorreu bem
                                StatusLabel.Text = "Todas imagens carregadas com sucesso!";
                            }
                            else
                            {
                                // Mensagem notifica que é permitido carregar apenas
                                // as imagens definida la em cima.
                                StatusLabel.Text = "É permitido carregar apenas imagens!";
                            }
                        }
                        catch (Exception ex)
                        {
                            // Mensagem notifica quando ocorre erros
                            StatusLabel.Text = "O arquivo não pôde ser carregado. O seguinte erro ocorreu: " + ex.Message;
                        }
                    }
                }
                catch (Exception ex)
                {
                    // Mensagem notifica quando ocorre erros
                    StatusLabel.Text = "O arquivo não pôde ser carregado. O seguinte erro ocorreu: " + ex.Message;
                }
            }
            else
            {
                // Mensagem notifica quando imagem é superior a 8 MB
                StatusLabel.Text = "Não é permitido carregar mais do que 8 MB";
            }

            SqlCommand command = new SqlCommand("insert into t_catalogo (TipoCatalogo, Titulo, Descricao, AnoLancamento, F_Genero, Direcao, Duracao, DataInsercao, Foto) values ('" + dpTipoCatalogo.Text + "', '" + txtTituloFilme.Text + "', '" + txtSinopseFilme.Text + "', '" + txtAnoLancamento.Text + "', '" + dpGeneroFilme.Text + "', '" + txtDirecaoFilme.Text + "', '" + txtDuracao.Text + "', SYSDATETIME(), '" + pth + "')", con);

            try
            {
                command.ExecuteNonQuery();

                Response.Write("<script>alert('Filme Cadastrado Com Sucesso!');location = 'cadastroFilme.aspx';</script>");
                Limpar(this);
            }
            catch (SqlException)
            {
                Response.Write("<script>alert('Não foi possível realizar o cadastro. Verifique os dados e tente novamente!');</script>");
            }



            con.Close();
        }
コード例 #48
0
ファイル: UploadController.cs プロジェクト: doct15/blogengine
 private void UploadVideo(string virtualFolder, HttpPostedFile file, string fileName)
 {
     var folder = HttpContext.Current.Server.MapPath(virtualFolder);
     if (!Directory.Exists(folder))
     {
         Directory.CreateDirectory(folder);
     }
     file.SaveAs(folder + fileName);
 }
コード例 #49
0
        public HttpResponseMessage UploadFile(long?id, int Category)
        {
            HttpPostedFile postedFile = HttpContext.Current.Request.Files[0];

            Car car         = db.Cars.Find(id);
            var CarCategory = car.Carcategories.Where(cat => cat.CategoryId == Category).FirstOrDefault();


            if (postedFile.ContentLength > 0)
            {
                string extension  = System.IO.Path.GetExtension(postedFile.FileName).ToLower();
                string query      = null;
                string connString = "";



                string[] validFileTypes = { ".xls", ".xlsx" };

                string filePath = string.Format("{0}/{1}", HttpContext.Current.Server.MapPath("~/Content/Uploads"), postedFile.FileName);
                if (!Directory.Exists(filePath))
                {
                    Directory.CreateDirectory(HttpContext.Current.Server.MapPath("~/Content/Uploads"));
                }
                if (validFileTypes.Contains(extension))
                {
                    if (System.IO.File.Exists(filePath))
                    {
                        System.IO.File.Delete(filePath);
                    }
                    postedFile.SaveAs(filePath);
                    if (extension.Trim() == ".xls")
                    {
                        connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
                    }
                    else if (extension.Trim() == ".xlsx")
                    {
                        connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
                    }
                    OleDbConnection oledbConn = new OleDbConnection(connString);
                    DataTable       dt        = new DataTable();
                    try
                    {
                        oledbConn.Open();
                        using (OleDbCommand cmd = new OleDbCommand("SELECT * FROM [Sheet1$]", oledbConn))
                        {
                            OleDbDataAdapter oleda = new OleDbDataAdapter();
                            oleda.SelectCommand = cmd;
                            DataSet ds = new DataSet();
                            oleda.Fill(ds);

                            dt = ds.Tables[0];
                        }

                        #region Region


                        CarCategory.EngineCapacity = int.Parse(dt.Rows[0]["EngineCapacity"].ToString());


                        CarCategory.TransfersNo = int.Parse(dt.Rows[0]["TransfersNo"].ToString());


                        CarCategory.CylindersNo = int.Parse(dt.Rows[0]["CylindersNo"].ToString());


                        CarCategory.CastingsNo = int.Parse(dt.Rows[0]["CastingsNo"].ToString());


                        CarCategory.ElectronicFuelInjection = dt.Rows[0]["ElectronicFuelInjection"].ToString() == "0" ? false : true;


                        CarCategory.MaximumTorque = dt.Rows[0]["MaximumTorque"].ToString();


                        CarCategory.EnginePower = dt.Rows[0]["EnginePower"].ToString();


                        CarCategory.Acceleration = int.Parse(dt.Rows[0]["Acceleration"].ToString());


                        CarCategory.TractionType = dt.Rows[0]["TractionType"].ToString();


                        CarCategory.SeatsNo = int.Parse(dt.Rows[0]["SeatsNo"].ToString());


                        CarCategory.DoorsNo = int.Parse(dt.Rows[0]["DoorsNo"].ToString());


                        CarCategory.AvgFuelConsumption = int.Parse(dt.Rows[0]["AvgFuelConsumption"].ToString());


                        CarCategory.FuelTankCapacity = int.Parse(dt.Rows[0]["FuelTankCapacity"].ToString());


                        CarCategory.GroundClearance = int.Parse(dt.Rows[0]["GroundClearance"].ToString());


                        CarCategory.MaxSpeed = int.Parse(dt.Rows[0]["MaxSpeed"].ToString());


                        CarCategory.FuelRecommended = dt.Rows[0]["FuelRecommended"].ToString();


                        CarCategory.DriverAirbags = dt.Rows[0]["DriverAirbags"].ToString() == "0" ? false : true;


                        CarCategory.FrontPassengerAirbags = dt.Rows[0]["FrontPassengerAirbags"].ToString() == "0" ? false : true;


                        CarCategory.ElectricChairs = dt.Rows[0]["ElectricChairs"].ToString() == "0" ? false : true;


                        CarCategory.BrakeSystemABS = dt.Rows[0]["BrakeSystemABS"].ToString() == "0" ? false : true;


                        CarCategory.ElectronicBrakeDistribution = dt.Rows[0]["ElectronicBrakeDistribution"].ToString() == "0" ? false : true;


                        CarCategory.ElectronicBalanceProgram = dt.Rows[0]["ElectronicBalanceProgram"].ToString() == "0" ? false : true;


                        CarCategory.AntitheftAlarmSystem = dt.Rows[0]["AntitheftAlarmSystem"].ToString() == "0" ? false : true;


                        CarCategory.ImmobilizerSystemAgainstTheft = dt.Rows[0]["ImmobilizerSystemAgainstTheft"].ToString() == "0" ? false : true;


                        CarCategory.SportRims = dt.Rows[0]["SportRims"].ToString() == "0" ? false : true;


                        CarCategory.RimSize = int.Parse(dt.Rows[0]["RimSize"].ToString());


                        CarCategory.FrontFogLanterns = dt.Rows[0]["FrontFogLanterns"].ToString() == "0" ? false : true;


                        CarCategory.BackFogLanterns = dt.Rows[0]["BackFogLanterns"].ToString() == "0" ? false : true;


                        CarCategory.BackCleaners = dt.Rows[0]["BackCleaners"].ToString() == "0" ? false : true;


                        CarCategory.ElectricSideMirrors = dt.Rows[0]["ElectricSideMirrors"].ToString() == "0" ? false : true;


                        CarCategory.ElectricallyFoldingSideMirrors = dt.Rows[0]["ElectricallyFoldingSideMirrors"].ToString() == "0" ? false : true;


                        CarCategory.SideMirrorsSignals = dt.Rows[0]["SideMirrorsSignals"].ToString() == "0" ? false : true;


                        CarCategory.XenonBulbsLighting = dt.Rows[0]["XenonBulbsLighting"].ToString() == "0" ? false : true;


                        CarCategory.HeadlampWipers = dt.Rows[0]["HeadlampWipers"].ToString() == "0" ? false : true;


                        CarCategory.SensitiveHeadlamps = dt.Rows[0]["SensitiveHeadlamps"].ToString() == "0" ? false : true;


                        CarCategory.HeadlampControl = dt.Rows[0]["HeadlampControl"].ToString() == "0" ? false : true;


                        CarCategory.HeadlampLightingLED = dt.Rows[0]["HeadlampLightingLED"].ToString() == "0" ? false : true;


                        CarCategory.TaillightsLightingLED = dt.Rows[0]["TaillightsLightingLED"].ToString() == "0" ? false : true;


                        CarCategory.BackSpoiler = dt.Rows[0]["BackSpoiler"].ToString() == "0" ? false : true;


                        CarCategory.IntelligentParkingSystem = dt.Rows[0]["IntelligentParkingSystem"].ToString() == "0" ? false : true;


                        CarCategory.SoundSystem = dt.Rows[0]["SoundSystem"].ToString() == "0" ? false : true;


                        CarCategory.CDDriver = dt.Rows[0]["CDDriver"].ToString() == "0" ? false : true;


                        CarCategory.AUXPort = dt.Rows[0]["AUXPort"].ToString() == "0" ? false : true;


                        CarCategory.USBPort = dt.Rows[0]["USBPort"].ToString() == "0" ? false : true;


                        CarCategory.Bluetooth = dt.Rows[0]["Bluetooth"].ToString() == "0" ? false : true;


                        CarCategory.FrontHeadrests = dt.Rows[0]["FrontHeadrests"].ToString() == "0" ? false : true;


                        CarCategory.RearHeadrests = dt.Rows[0]["RearHeadrests"].ToString() == "0" ? false : true;


                        CarCategory.ElectricWindshield = dt.Rows[0]["ElectricWindshield"].ToString() == "0" ? false : true;


                        CarCategory.ElectricRearGlass = dt.Rows[0]["ElectricRearGlass"].ToString() == "0" ? false : true;


                        CarCategory.OneTouchGlassControl = dt.Rows[0]["OneTouchGlassControl"].ToString() == "0" ? false : true;


                        CarCategory.RemoteControlToLockAndOpenDoors = dt.Rows[0]["RemoteControlToLockAndOpenDoors"].ToString() == "0" ? false : true;


                        CarCategory.DriverHeightControl = dt.Rows[0]["DriverHeightControl"].ToString() == "0" ? false : true;


                        CarCategory.LeatherBrushes = dt.Rows[0]["LeatherBrushes"].ToString() == "0" ? false : true;


                        CarCategory.EngineStartStopButtonSystem = dt.Rows[0]["EngineStartStopButtonSystem"].ToString() == "0" ? false : true;


                        CarCategory.Sunroof = dt.Rows[0]["Sunroof"].ToString() == "0" ? false : true;


                        CarCategory.ElectricSunroof = dt.Rows[0]["ElectricSunroof"].ToString() == "0" ? false : true;


                        CarCategory.BackCamera = dt.Rows[0]["BackCamera"].ToString() == "0" ? false : true;


                        CarCategory.ComputerTrips = dt.Rows[0]["ComputerTrips"].ToString() == "0" ? false : true;


                        CarCategory.SteeringWheelType = dt.Rows[0]["SteeringWheelType"].ToString() == "0" ? false : true;


                        CarCategory.ControllableSteeringWheel = dt.Rows[0]["ControllableSteeringWheel"].ToString() == "0" ? false : true;


                        CarCategory.ControlTheSoundSystemOfTheSteeringWheel = dt.Rows[0]["ControlTheSoundSystemOfTheSteeringWheel"].ToString() == "0" ? false : true;


                        CarCategory.CruiseControl = dt.Rows[0]["CruiseControl"].ToString() == "0" ? false : true;


                        CarCategory.LeatherSteeringWheel = dt.Rows[0]["LeatherSteeringWheel"].ToString() == "0" ? false : true;


                        CarCategory.LeatherTransmission = dt.Rows[0]["LeatherTransmission"].ToString() == "0" ? false : true;


                        CarCategory.FrontDoorStorage = dt.Rows[0]["FrontDoorStorage"].ToString() == "0" ? false : true;


                        CarCategory.BackDoorStorageAreas = dt.Rows[0]["BackDoorStorageAreas"].ToString() == "0" ? false : true;


                        CarCategory.PossibilityToFoldBackSeats = dt.Rows[0]["PossibilityToFoldBackSeats"].ToString() == "0" ? false : true;


                        CarCategory.Lighter = dt.Rows[0]["Lighter"].ToString() == "0" ? false : true;


                        CarCategory.MobileAshtray = dt.Rows[0]["MobileAshtray"].ToString() == "0" ? false : true;


                        CarCategory.CentralDoorLock = dt.Rows[0]["CentralDoorLock"].ToString() == "0" ? false : true;


                        CarCategory.AlarmSoundWhenTheCarIsNotClosed = dt.Rows[0]["AlarmSoundWhenTheCarIsNotClosed"].ToString() == "0" ? false : true;


                        CarCategory.FrontCupHolder = dt.Rows[0]["FrontCupHolder"].ToString() == "0" ? false : true;


                        CarCategory.BackCupHolder = dt.Rows[0]["BackCupHolder"].ToString() == "0" ? false : true;


                        CarCategory.FrontArmrest = dt.Rows[0]["FrontArmrest"].ToString() == "0" ? false : true;


                        CarCategory.AirConditionedFrontArmrest = dt.Rows[0]["AirConditionedFrontArmrest"].ToString() == "0" ? false : true;


                        CarCategory.BackArmrest = dt.Rows[0]["BackArmrest"].ToString() == "0" ? false : true;


                        CarCategory.BackTrunkCover = dt.Rows[0]["BackTrunkCover"].ToString() == "0" ? false : true;


                        CarCategory.FrontStorageDrawer = dt.Rows[0]["FrontStorageDrawer"].ToString() == "0" ? false : true;


                        CarCategory.PowerOutlet = dt.Rows[0]["PowerOutlet"].ToString() == "0" ? false : true;


                        CarCategory.BackOutletPowerOutlet = dt.Rows[0]["BackOutletPowerOutlet"].ToString() == "0" ? false : true;


                        CarCategory.BackWipers = dt.Rows[0]["BackWipers"].ToString() == "0" ? false : true;


                        CarCategory.RainSensitiveWindshieldWipers = dt.Rows[0]["RainSensitiveWindshieldWipers"].ToString() == "0" ? false : true;

                        CarCategory.BackLight = dt.Rows[0]["BackLight"].ToString() == "0" ? false : true;

                        CarCategory.SensitiveHeadlampsForLighting = dt.Rows[0]["SensitiveHeadlampsForLighting"].ToString() == "0" ? false : true;

                        CarCategory.BackTrunkSpace = dt.Rows[0]["BackTrunkSpace"].ToString() == "0" ? false : true;

                        CarCategory.BackSeatBelt = dt.Rows[0]["BackSeatBelt"].ToString() == "0" ? false : true;
                        #endregion

                        db.SaveChanges();
                    }
                    catch (Exception ex)
                    {
                        throw (ex);
                    }
                    finally
                    {
                        oledbConn.Close();
                    }
                }
            }


            //Send OK Response to Client.
            return(Request.CreateResponse());
        }
コード例 #50
0
ファイル: UpLoad.cs プロジェクト: priceLiu/CMS
    ///<summary>
    /// 文件上传方法
    /// </summary>
    public string fileSaveAs(HttpPostedFile _postedFile, int _isWater)
    {
        try
            {
                string _fileExt = _postedFile.FileName.Substring(_postedFile.FileName.LastIndexOf(".") + 1);
                //验证合法的文件
                if (!CheckFileExt(this.fileType, _fileExt))
                {
                    return "{\"msg\": 1, \"msbox\": \"不允许上传" + _fileExt + "类型的文件!\"}";
                }
                if (this.fileSize > 0 && _postedFile.ContentLength > fileSize * 1024)
                {
                    return "{\"msg\": 1, \"msbox\": \"文件超过限制的大小啦!\"}";
                }
                string _fileName = DateTime.Now.ToString("yyyyMMddHHmmssff") + "." + _fileExt; //随机文件名
                //检查保存的路径 是否有/开头结尾
                if (this.filePath.StartsWith("/") == false) this.filePath = "/" + this.filePath;
                if (this.filePath.EndsWith("/") == false) this.filePath = this.filePath + "/";
                //按日期归类保存
                string _datePath = DateTime.Now.ToString("yyyyMMdd") + "/";
                this.filePath += _datePath;
                //获得要保存的文件路径
                string serverFileName = this.filePath + _fileName;
                //物理完整路径
                string toFileFullPath = HttpContext.Current.Server.MapPath(this.filePath);
                //检查是否有该路径没有就创建
                if (!Directory.Exists(toFileFullPath))
                {
                    Directory.CreateDirectory(toFileFullPath);
                }
                //将要保存的完整文件名
                string toFile = toFileFullPath + _fileName;
                //保存文件
                _postedFile.SaveAs(toFile);

                //是否打图片水印
                if (isWatermark > 0 && _isWater == 1 && CheckFileExt("BMP|JPEG|JPG|GIF|PNG|TIFF", _fileExt))
                {
                    switch (isWatermark)
                    {
                        case 1:
                            ImageWaterMark.AddImageSignText(serverFileName, this.filePath + _fileName, this.textWater, waterStatus, waterQuality, textWaterFont, textFontSize);
                            break;
                        case 2:
                            ImageWaterMark.AddImageSignPic(serverFileName, this.filePath + _fileName, this.imgWaterPath, waterStatus, waterQuality, waterTransparency);
                            break;
                    }
                }
                return "{\"msg\": 1, \"msbox\": \"" + serverFileName + "\"}";
            }
            catch
            {
                return "{\"msg\": 1, \"msbox\": \"上传过程中发生意外错误!\"}";
            }
    }
コード例 #51
0
ファイル: PM_CNFB.aspx.cs プロジェクト: 2644783865/TJ_UPGRADE
        protected void btn_import_Click(object sender, EventArgs e)
        {
            if (tbyear.Text.ToString() == "" || tbmonth.Text.ToString() == "")
            {
                Response.Write("<script>alert('请填写数据对应的年月!');</script>"); return;
            }
            List <string> list     = new List <string>();
            string        FilePath = @"E:\厂内分包表\";

            if (!Directory.Exists(FilePath))
            {
                Directory.CreateDirectory(FilePath);
            }
            //将文件上传到服务器
            HttpPostedFile UserHPF = FileUpload1.PostedFile;

            try
            {
                string fileContentType = UserHPF.ContentType;// 获取客户端发送的文件的 MIME 内容类型
                if (fileContentType == "application/vnd.ms-excel")
                {
                    if (UserHPF.ContentLength > 0)
                    {
                        UserHPF.SaveAs(FilePath + "//" + System.IO.Path.GetFileName(UserHPF.FileName));//将上传的文件存放在指定的文件夹中
                    }
                }
                else
                {
                    Response.Write("<script>alert('文件类型不符合要求,请您核对后重新上传!');</script>"); return;
                }
            }
            catch
            {
                Response.Write("<script>alert('文件上传过程中出现错误!');</script>"); return;
            }

            using (FileStream fs = File.OpenRead(FilePath + "//" + System.IO.Path.GetFileName(UserHPF.FileName)))
            {
                //根据文件流创建一个workbook
                IWorkbook wk = new HSSFWorkbook(fs);

                //获取第一个工作表
                ISheet sheet1 = wk.GetSheetAt(0);
                ISheet sheet2 = wk.GetSheetAt(1);


                //循环读取每一行数据,由于execel有列名以及序号,从1开始
                string cnfbyear  = tbyear.Text.ToString();
                string cnfbmonth = tbmonth.Text.ToString();

                string sqlTextchk           = "select * from TBMP_CNFB_LIST where CNFB_YEAR='" + cnfbyear + "' and CNFB_MONTH='" + cnfbmonth + "'";
                System.Data.DataTable dtchk = DBCallCommon.GetDTUsingSqlText(sqlTextchk);
                if (dtchk.Rows.Count > 0)
                {
                    Response.Write("<script>alert('该月数据已导入,若想重新导入,请删除原有数据!');</script>"); return;
                }
                //结构车间
                for (int i = 2; i < sheet1.LastRowNum + 1; i++)
                {
                    string sql1  = "";
                    IRow   row1  = sheet1.GetRow(i);
                    ICell  cell0 = row1.GetCell(0);
                    if (cell0.NumericCellValue > 0)
                    {
                        ICell cell1 = row1.GetCell(1);
                        ICell cell2 = row1.GetCell(2);
                        ICell cell3 = row1.GetCell(3);
                        ICell cell4 = row1.GetCell(4);
                        ICell cell5 = row1.GetCell(5);
                        //ICell cell6 = row1.GetCell(6);
                        ICell cell11 = row1.GetCell(11);
                        ICell cell12 = row1.GetCell(12);
                        ICell cell13 = row1.GetCell(13);
                        if (cell1 == null)
                        {
                            sql1 += "'" + "" + "',";
                        }
                        else
                        {
                            sql1 += "'" + cell1.ToString().Trim() + "',";
                        }
                        if (cell2 == null)
                        {
                            sql1 += "'" + "" + "',";
                        }
                        else
                        {
                            sql1 += "'" + cell2.ToString().Trim() + "',";
                        }
                        if (cell3 == null)
                        {
                            sql1 += "'" + "" + "',";
                        }
                        else
                        {
                            sql1 += "'" + cell3.ToString().Trim() + "',";
                        }
                        if (cell4 == null)
                        {
                            sql1 += "'" + "" + "',";
                        }
                        else
                        {
                            string abcde = "";
                            try
                            {
                                sql1 += "'" + cell4.ToString().Trim() + "',";
                            }
                            catch
                            {
                                sql1 += "'" + cell4.NumericCellValue.ToString().Trim() + "',";
                            }
                        }
                        if (cell5 == null)
                        {
                            sql1 += "'" + "" + "',";
                        }
                        else
                        {
                            sql1 += "'" + cell5.ToString().Trim() + "',";
                        }
                        //sql1 += "'" + Convert.ToDouble(cell6.NumericCellValue.ToString()) + "',";
                        sql1 += "'" + Convert.ToDouble(cell11.NumericCellValue.ToString().Trim()) + "',";
                        sql1 += "'" + Convert.ToDouble(cell12.NumericCellValue.ToString().Trim()) + "',";
                        sql1 += "'" + cell13.ToString().Trim() + "',";
                        sql1 += "'" + cnfbyear.ToString().Trim() + "',";
                        sql1 += "'" + cnfbmonth.ToString().Trim() + "',GETDATE()";
                        string sqltext1 = "insert into TBMP_CNFB_LIST(CNFB_PROJNAME,CNFB_HTID,CNFB_TSAID,CNFB_TH,CNFB_SBNAME,CNFB_BYMYMONEY,CNFB_BYREALMONEY,CNFB_TYPE,CNFB_YEAR,CNFB_MONTH,CNFB_DRTIME) values(" + sql1 + ")";
                        list.Add(sqltext1);
                    }
                    else
                    {
                        break;
                    }
                }
                //喷漆喷砂
                for (int j = 2; j < sheet2.LastRowNum + 1; j++)
                {
                    string sql2  = "";
                    IRow   row2  = sheet2.GetRow(j);
                    ICell  cell0 = row2.GetCell(0);
                    if (cell0.NumericCellValue > 0)
                    {
                        ICell cell1 = row2.GetCell(1);
                        ICell cell2 = row2.GetCell(2);
                        ICell cell3 = row2.GetCell(3);
                        ICell cell4 = row2.GetCell(4);
                        ICell cell5 = row2.GetCell(5);
                        //ICell cell6 = row2.GetCell(6);
                        ICell  cell10 = row2.GetCell(10);
                        ICell  cell12 = row2.GetCell(12);
                        string zb     = "喷漆喷砂";
                        if (cell1 == null)
                        {
                            sql2 += "'" + "" + "',";
                        }
                        else
                        {
                            sql2 += "'" + cell1.ToString().Trim() + "',";
                        }
                        if (cell2 == null)
                        {
                            sql2 += "'" + "" + "',";
                        }
                        else
                        {
                            sql2 += "'" + cell2.ToString().Trim() + "',";
                        }
                        if (cell3 == null)
                        {
                            sql2 += "'" + "" + "',";
                        }
                        else
                        {
                            sql2 += "'" + cell3.ToString().Trim() + "',";
                        }
                        if (cell4 == null)
                        {
                            sql2 += "'" + "" + "',";
                        }
                        else
                        {
                            sql2 += "'" + cell4.ToString().Trim() + "',";
                        }
                        if (cell5 == null)
                        {
                            sql2 += "'" + "" + "',";
                        }
                        else
                        {
                            sql2 += "'" + cell5.ToString().Trim() + "',";
                        }
                        //sql2 += "'" + Convert.ToDouble(cell6.NumericCellValue.ToString()) + "',";
                        sql2 += "'" + Convert.ToDouble(cell10.NumericCellValue.ToString().Trim()) + "',";
                        sql2 += "'" + Convert.ToDouble(cell12.NumericCellValue.ToString().Trim()) + "',";
                        sql2 += "'" + zb.ToString().Trim() + "',";
                        sql2 += "'" + cnfbyear.ToString().Trim() + "',";
                        sql2 += "'" + cnfbmonth.ToString().Trim() + "',GETDATE()";
                        string sqltext2 = "insert into TBMP_CNFB_LIST(CNFB_PROJNAME,CNFB_HTID,CNFB_TSAID,CNFB_TH,CNFB_SBNAME,CNFB_BYMYMONEY,CNFB_BYREALMONEY,CNFB_TYPE,CNFB_YEAR,CNFB_MONTH,CNFB_DRTIME) values(" + sql2 + ")";
                        list.Add(sqltext2);
                    }
                    else
                    {
                        break;
                    }
                }
            }
            DBCallCommon.ExecuteTrans(list);

            foreach (string fileName in Directory.GetFiles(FilePath))//清空该文件夹下的文件
            {
                string newName = fileName.Substring(fileName.LastIndexOf("\\") + 1);
                System.IO.File.Delete(FilePath + "\\" + newName);//删除文件下储存的文件
            }
            bindGrid();
            Response.Redirect(Request.Url.ToString());
        }