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; } }
/// <summary> /// 是否允许 /// </summary> public static bool IsAllowedExtension(HttpPostedFile oFile, FileExtension[] fileEx) { int fileLen = oFile.ContentLength; byte[] imgArray = new byte[fileLen]; oFile.InputStream.Read(imgArray, 0, fileLen); MemoryStream ms = new MemoryStream(imgArray); System.IO.BinaryReader br = new System.IO.BinaryReader(ms); string fileclass = ""; byte buffer; try { buffer = br.ReadByte(); fileclass = buffer.ToString(); buffer = br.ReadByte(); fileclass += buffer.ToString(); } catch { } br.Close(); ms.Close(); foreach (FileExtension fe in fileEx) { if (Int32.Parse(fileclass) == (int)fe) return true; } return false; }
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("文件格式错误"); } }
public static int imageUpload(HttpPostedFile uploadFile) { int count=0; string filename = HttpUtility.HtmlEncode(uploadFile.FileName.ToLower()); string extension = Path.GetExtension(filename); if (extension == ".jpg" || extension == ".png" || extension == ".jpeg" || extension == ".bmp" || extension == ".gif") { Image uploadedImg = Image.FromStream(uploadFile.InputStream); float fuWidth = uploadedImg.PhysicalDimension.Width; float fuHeight = uploadedImg.PhysicalDimension.Height; if (fuWidth < 300|| fuHeight < 200) //The max height and width { count++; } } else { count++; } return count; }
public async Task UploadToYouTube(HttpPostedFile postedFile, string title) { UploadingDispatcher.SetProgress(uploadId, 2); Video video = new Video(); video.Title = title; video.Tags.Add(new MediaCategory("Autos", YouTubeNameTable.CategorySchema)); video.Private = false; video.MediaSource = new MediaFileSource(postedFile.InputStream, postedFile.FileName, postedFile.ContentType); var link = new AtomLink("http://uploads.gdata.youtube.com/resumable/feeds/api/users/default/uploads"); link.Rel = ResumableUploader.CreateMediaRelation; video.YouTubeEntry.Links.Add(link); var youtubeApiKey = ConfigurationManager.AppSettings["youtubeApiKey"]; var applicationName = ConfigurationManager.AppSettings["applicationName"]; var youtubeUserName = ConfigurationManager.AppSettings["youtubeUserName"]; var youtubePassword = ConfigurationManager.AppSettings["youtubePassword"]; var youtubeChunksize = int.Parse(ConfigurationManager.AppSettings["youtubeChunksize"]); var resumableUploader = new ResumableUploader(youtubeChunksize); resumableUploader.AsyncOperationCompleted += resumableUploader_AsyncOperationCompleted; resumableUploader.AsyncOperationProgress += resumableUploader_AsyncOperationProgress; var youTubeAuthenticator = new ClientLoginAuthenticator(applicationName, ServiceNames.YouTube, youtubeUserName, youtubePassword); youTubeAuthenticator.DeveloperKey = youtubeApiKey; resumableUploader.InsertAsync(youTubeAuthenticator, video.YouTubeEntry, uploadId); }
public string UpLoadFile(HttpPostedFile inputFile, string filePath, string myfileName) { if (string.IsNullOrEmpty(filePath)) { throw new ApplicationException("路径不能为空"); } if (string.IsNullOrEmpty(myfileName)) { throw new ApplicationException("文件名不能为空"); } FileUpLoad fp = new FileUpLoad(); //建立上传对象 HttpPostedFile postedFile = inputFile; FileName = System.IO.Path.GetFileName(postedFile.FileName); FileExtension = System.IO.Path.GetExtension(FileName).ToUpper(); //如果格式都不符合则返回 if (!".JPG".Equals(FileExtension) && !".JPEG".Equals(FileExtension) && !".PNG".Equals(FileExtension) ) { throw new ApplicationException("上传图片格式正确,请选择jpg,png格式的图片"); } if (postedFile.ContentLength > 1024 * 1024 * 20) { throw new ApplicationException("最大只能上传20M文件"); } if (myfileName != string.Empty) { FileName = myfileName+FileExtension; } string phyPath = HttpContext.Current.Server.MapPath("upload"); //判断路径是否存在,若不存在则创建路径 DirectoryInfo upDir = new DirectoryInfo(phyPath); if (!upDir.Exists) { upDir.Create(); } try { string tempPath = Path.Combine(phyPath, filePath); string originalImagePath = Path.Combine(tempPath, FileName); string thumbnailPath = Path.Combine(tempPath,"thumbnail_" + FileName); //保存源文件 postedFile.SaveAs(originalImagePath); ImageHelper.MakeThumbnail(originalImagePath, thumbnailPath,80,80,"W"); } catch { throw new ApplicationException("上传失败!"); } return "/upload/" + filePath + "/thumbnail_" + FileName; }
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; }
/** * 上传文件的主处理方法 * @param HttpContext * @param string * @param string[] *@param int * @return Hashtable */ public Hashtable upFile(HttpContext cxt, string pathbase, string[] filetype, int size, string progresskey) { var dateTimeStr = DateTime.Now.ToString("yyyy-MM-dd"); pathbase = pathbase + dateTimeStr + "/"; uploadpath = cxt.Server.MapPath(pathbase);//获取文件上传路径 try { uploadFile = cxt.Request.Files[0]; originalName = uploadFile.FileName; //目录创建 createFolder(); //格式验证 if (checkType(filetype)) { state = "不允许的文件类型"; } else if (checkSize(size))/*大小验证*/ { state = "文件大小超出限制"; } //保存图片 if (state.Equals("1")) { filename = reName(); using (FileStream fs = new FileStream(uploadpath + filename, FileMode.Create)) { byte[] buffer = new byte[92160]; int progress = 0; int contentLength = uploadFile.ContentLength; while (progress < contentLength) { int bytes = uploadFile.InputStream.Read(buffer, 0, buffer.Length); fs.Write(buffer, 0, bytes); progress += bytes; //记录上传进度 if (progresskey != null && progresskey.Length > 0) { HttpContext.Current.Cache[progresskey] = (int)(((decimal)progress) / contentLength * 100); } } } URL = pathbase + filename; path = dateTimeStr + "/" + filename; } } catch (Exception e) { state = "未知错误"; URL = ""; } return getUploadInfo(); }
public bool ValidateUserImageDimensions(HttpPostedFile file) { using (Bitmap bitmap = new Bitmap(file.InputStream, false)) { if (bitmap.Height > 50) return false; else return true; } }
protected void SaveZipFile(long userId, HttpPostedFile file) { FileModule fileModule = new FileModule(); string filename = file.FileName; string extension = System.IO.Path.GetExtension(file.FileName.ToLower()); if (extension != ".zip") throw new Exception("You can only upload zip files."); hidden_uploaded_file_ID.Value = fileModule.saveFileForUserId(userId, file.InputStream, FILE_TYPE.ZIP, file.FileName).UPLOADEDFILE_ID.ToString(); hidden_uploaded_file_name.Value = filename; }
public static bool checkFileSize(HttpPostedFile FilePost, int FileSize) { int nLimitSize = 0; nLimitSize = 1024000 * FileSize; bool bCheckImage = false; HttpPostedFile upPhoto = FilePost; if (upPhoto.ContentLength > nLimitSize) // OverFlow bCheckImage = false; else bCheckImage = true; return bCheckImage; ; }
/** * 上传文件的主处理方法 * @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(); }
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); } }
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; } }
/** * 上传文件的主处理方法 * @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(); }
public static string UploadFile(HttpPostedFile fileUpload, string fileName, HttpContext context, string uploadId) { var uploadPath = context.Server.MapPath("~/IMAGES_TEMP"); var fileId = Guid.NewGuid().ToString(); using ( var fs = new FileStream(Path.Combine(uploadPath, fileId), FileMode.Create)) { var buffer = new byte[fileUpload.InputStream.Length]; fileUpload.InputStream.Read(buffer, 0, buffer.Length); fs.Write(buffer, 0, buffer.Length); } /* ----Insert into DB ---- */ /* ----------------------- */ return fileId; }
/** * 上传文件的主处理方法 * @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(); }
/** * �ϴ��ļ������������ * @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(); }
//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; }
protected void Button1_Click(object sender, EventArgs e) { SqlConnection connection2 = Connect(s_data); //string sql2 = $"insert into [Products](productName,picture,category,inventory,price) values(@pn,@pc,@c,@i,@pr)"; bool inventoryCheck = Regex.IsMatch(TextBox4.Text, @"\d"); bool priceCheck = Regex.IsMatch(TextBox5.Text, @"\d"); if (TextBox1.Text != "") { if (TextBox3.Text != "") { if (inventoryCheck) { if (priceCheck) { if (FileUpload1.PostedFile != null) { HttpPostedFile myFile = FileUpload1.PostedFile; int nFileLen = myFile.ContentLength; if (FileUpload1.HasFile && nFileLen > 0) { string picturePath0 = $@"images\衣服\{TextBox1.Text}_{TextBox3.Text}.jpg"; string picturePath1 = $@"images\衣服\{TextBox1.Text}_{TextBox3.Text}.jpg"; string imgPath = Server.MapPath(picturePath1); FileUpload1.SaveAs(imgPath); string sql2 = $"insert into [Products](productName,picture,category,inventory,price) values(N'{TextBox1.Text}',N'{picturePath0}',N'{TextBox3.Text}','{TextBox4.Text}','{TextBox5.Text}')"; SqlCommand command2 = new SqlCommand(sql2, connection2); connection2.Open(); command2.ExecuteNonQuery(); this.Page.ClientScript.RegisterStartupScript(this.Page.GetType(), "bt1", "setTimeout( function(){alert('輸入成功');},0);", true); connection2.Close(); reviewProduct(); cleanbt1(); cleanbt2(); cleanbt3(); } else { hintPicture.ForeColor = Color.Red; hintPicture.Text = "picture尚未選擇 請選擇上傳圖片"; } } else { hintPicture.ForeColor = Color.Red; hintPicture.Text = "picture尚未選擇 請選擇上傳圖片"; } } else { hintPrice.ForeColor = Color.Red; hintPrice.Text = "price需為數字 請重新輸入"; } } else { hintInventory.ForeColor = Color.Red; hintInventory.Text = "inventory需為數字 請重新輸入"; } } else { hintCategory.ForeColor = Color.Red; hintCategory.Text = "category不得為空"; } } else { hintPN.ForeColor = Color.Red; hintPN.Text = "productName不得為空"; } /*try * { * command2.Parameters.Add("@pn", SqlDbType.NVarChar); * command2.Parameters["@pn"].Value = TextBox1.Text; * command2.Parameters.Add("@pc", SqlDbType.NVarChar); * command2.Parameters["@pc"].Value = TextBox2.Text; * command2.Parameters.Add("@c", SqlDbType.NVarChar); * command2.Parameters["@c"].Value = TextBox3.Text; * command2.Parameters.Add("@i", SqlDbType.Int); * command2.Parameters.Add("@pr", SqlDbType.Int); * command2.Parameters["@i"].Value = Convert.ToInt32(TextBox4.Text); * command2.Parameters["@pr"].Value = Convert.ToInt32(TextBox5.Text); * command2.ExecuteNonQuery(); * MessageBox.Show("Done"); * } * catch (Exception ex) * { * MessageBox.Show("Pls enter number"); * }*/ //connection2.Close(); }
protected void Page_Load(object sender, EventArgs e) { //UploadService bb = new UploadService(); //bb.CreateCompanyDirectory("703dfb3c-d3dc-4b1d-9bf0-3507ba01b716", "集团本部", "SMT"); SMT.Foundation.Log.Tracer.Debug("开始上传文件时间:" + System.DateTime.Now.ToString()); try { string NewPath = ""; HttpPostedFile fileData = Request.Files["Filedata"]; SMT.Foundation.Log.Tracer.Debug("开始上传文件的大小:" + fileData.ContentLength.ToString()); SMT.Foundation.Log.Tracer.Debug("开始上传文件:" + fileData.FileName); string filePath = ""; string companyCode = ""; //公司代码 string systemCode = ""; //系统代码 string modelCode = ""; //模块代码 string encryptName = ""; //加密字符串 string strFileName = ""; strFileName = fileData.FileName; UserFile model = null; string DownloadUrl = string.Concat(ConfigurationManager.AppSettings["DownLoadUrl"]); //获取用户身份,由用户名,密码组成 string StrAuthUser = string.Concat(ConfigurationManager.AppSettings["FileUploadUser"]); //if (Request["path"] != null) //{ // filePath = Request["path"].ToString(); // SMT.Foundation.Log.Tracer.Debug("上传文件完成,路径:" + filePath); //} if (Request["companyCode"] != null)//公司代码 { companyCode = Request["companyCode"].ToString(); model = FileConfig.GetCompanyItem(companyCode); SMT.Foundation.Log.Tracer.Debug("aspx页面上传文件companyCode:" + companyCode); } if (Request["systemCode"] != null)//系统代码 { systemCode = Request["systemCode"].ToString(); SMT.Foundation.Log.Tracer.Debug("aspx页面上传文件systemcode:" + systemCode); } if (Request["modelCode"] != null)//模块代码 { modelCode = Request["modelCode"].ToString(); SMT.Foundation.Log.Tracer.Debug("aspx页面上传文件modlecode:" + modelCode); } if (Request["encryptName"] != null)//加密文件名 { encryptName = Request["encryptName"].ToString(); SMT.Foundation.Log.Tracer.Debug("aspx页面上传文件encryptName:" + encryptName); } if (fileData != null) { //string path = ctx.Server.MapPath(ctx.Request["file"].ToString()); string strPath = string.Format(model.SavePath, companyCode, systemCode, modelCode); if (!System.IO.Directory.Exists(strPath)) { if (strPath.IndexOf("\\\\") == 0) { string FirstName = ""; string UserName = ""; string StrPwd = ""; string ComputerName = ""; if (StrAuthUser.IndexOf(",") > 0) { FirstName = StrAuthUser.Split(',')[0]; ComputerName = FirstName.Split('/')[0]; UserName = FirstName.Split('/')[1]; StrPwd = StrAuthUser.Split(',')[1]; } LogonImpersonate imper = new LogonImpersonate(UserName, StrPwd); string path = @"Z:\" + companyCode + @"\" + systemCode + @"\" + modelCode; string OldPath = model.SavePath.Split('{')[0].TrimEnd('\\'); if (CreateDirectory(path, UserName, StrPwd, OldPath)) { SMT.Foundation.Log.Tracer.Debug("aspx页面创建了驱动器映射"); } else { SMT.Foundation.Log.Tracer.Debug("aspx页面有创建映射问题"); } } else { System.IO.Directory.CreateDirectory(strPath); } } NewPath = Path.Combine(strPath, encryptName); //还未上传完成的路径 string OldFilePath = Path.Combine(strPath, strFileName); //原来上传的文件 string PassWordKey = ""; //加密字符串 if (encryptName.Length > 8) { PassWordKey = encryptName.Substring(0, 8); } else { PassWordKey = "12345678"; } int fileLength = fileData.ContentLength; byte[] data = new Byte[fileLength]; Stream fileStream = fileData.InputStream; fileStream.Read(data, 0, fileLength); SMT.Foundation.Log.Tracer.Debug("aspx页面上传文件开始,路径NewPath:" + NewPath); using (FileStream fs = File.Create(NewPath)) { fs.Write(data, 0, data.Length); fs.Close(); fs.Dispose(); } //创建上传过来的文件 SMT.Foundation.Log.Tracer.Debug("aspx页面上传文件开始,路径OldFilePath:" + OldFilePath); using (FileStream fsOld = File.Create(OldFilePath)) { fsOld.Write(data, 0, data.Length); fsOld.Close(); fsOld.Dispose(); } string strTempName = Path.Combine(strPath, encryptName);//已经上传完成的路径 SMT.Foundation.Log.Tracer.Debug("aspx页面上传文件开始,路径strTempName:" + strTempName); File.Move(NewPath, strTempName); NewPath = strTempName;//最近返回已完成的路径 string imageType = ".JPEG,.JPG,.GIF,.BMP"; //判断上传的模块的类型,如果是新闻则生成缩略图 #region 生成缩略图 string FileType = ""; if (imageType.IndexOf(FileType) > 0 || imageType.ToLower().IndexOf(FileType) > 0) { string thumbPath = string.Format(model.SavePath, companyCode, systemCode, modelCode) + "\\thumb\\"; SMT.Foundation.Log.Tracer.Debug("aspx页面上传图片文件,路径thumbPath:" + thumbPath); if (!System.IO.Directory.Exists(thumbPath)) { SMT.Foundation.Log.Tracer.Debug("aspx页面上传图片文件,不存在路径thumbPath:" + thumbPath); if (strPath.IndexOf("\\\\") == 0) { string FirstName = ""; string UserName = ""; string StrPwd = ""; string ComputerName = ""; if (StrAuthUser.IndexOf(",") > 0) { FirstName = StrAuthUser.Split(',')[0]; ComputerName = FirstName.Split('/')[0]; UserName = FirstName.Split('/')[1]; StrPwd = StrAuthUser.Split(',')[1]; } LogonImpersonate imper = new LogonImpersonate(UserName, StrPwd); string path = @"Z:\" + companyCode + @"\" + systemCode + @"\" + modelCode; string OldPath = model.SavePath.Split('{')[0].TrimEnd('\\'); if (CreateDirectory(path, UserName, StrPwd, OldPath)) { SMT.Foundation.Log.Tracer.Debug("创建了驱动器映射"); } else { SMT.Foundation.Log.Tracer.Debug("aspx页面图片上传有问题"); } } else { SMT.Foundation.Log.Tracer.Debug("aspx页面上传图片文件,开始创建路径thumbPath:" + thumbPath); System.IO.Directory.CreateDirectory(thumbPath); } } string thumbFile = thumbPath + encryptName; string strType = "JPG"; strType = FileType; MakeImageThumb.MakeThumbnail(OldFilePath, thumbFile, 250, 200, "DB", strType); //保存到数据库的路径 string strSaveThumb = string.Format("\\{0}\\{1}\\{2}", companyCode, systemCode, modelCode + "\\thumb\\" + encryptName); //entity.THUMBNAILURL = string.Format("\\{0}\\{1}\\{2}", model.CompanyCode, model.SystemCode, model.ModelCode + "\\" + strMd5Name); //entity.THUMBNAILURL = strSaveThumb; } #endregion CryptoHelp.EncryptFileForMVC(OldFilePath, NewPath, PassWordKey); //fileStream.Close(); //fileStream.Dispose(); SMT.Foundation.Log.Tracer.Debug("aspx页面上传文件完成,路径:" + NewPath + " tempName:" + strTempName); } } catch (Exception ex) { SMT.Foundation.Log.Tracer.Debug("上传文件upload.aspx页面出现错误:" + ex.ToString()); } }
public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; context.Response.Charset = "utf-8"; try { HttpPostedFile FilePath = context.Request.Files["Filedata"]; string FileServerPath = HttpContext.Current.Server.MapPath("~") + "/Files"; string FileServerPathTask = HttpContext.Current.Server.MapPath("~") + "/Files/Evaluate/2"; string FileServerPathTaskSmall = HttpContext.Current.Server.MapPath("~") + "/Files/Evaluate/2/Small"; string FileServerPathTaskMiddle = HttpContext.Current.Server.MapPath("~") + "/Files/Evaluate/2/Middle"; if (FilePath != null) { if (!Directory.Exists(FileServerPath)) { Directory.CreateDirectory(FileServerPath); } } if (FileServerPathTask != null) { if (!Directory.Exists(FileServerPathTask)) { Directory.CreateDirectory(FileServerPathTask); } if (!Directory.Exists(FileServerPathTaskSmall)) { Directory.CreateDirectory(FileServerPathTaskSmall); } if (!Directory.Exists(FileServerPathTaskMiddle)) { Directory.CreateDirectory(FileServerPathTaskMiddle); } int size = FilePath.ContentLength; if (size / (1024 * 1024) >= 4) { context.Response.Write("<script>alert('文件超大!请精简该文件再执行导入操作!')</script>"); } else { string filename = DateTime.Now.ToString("yyyyMMddHHmmssffff");// + SysFunction.FsRandomString(10); string fileExt = FilePath.FileName.Substring(FilePath.FileName.LastIndexOf(".")); string FileServerFullPath = FileServerPathTask + "\\" + filename + fileExt; FilePath.SaveAs(FileServerFullPath); //下面这句代码缺少的话,上传成功后上传队列的显示不会自动消失 string newimg = "Files/Evaluate/2/" + filename + fileExt; context.Response.Write(newimg); //生成缩略图,中图 MakeThumbnail(FilePath.InputStream, FileServerPathTaskMiddle + "\\" + filename + fileExt, 367, 400, "W"); //生成缩略图,小图 MakeThumbnail(FilePath.InputStream, FileServerPathTaskSmall + "\\" + filename + fileExt, 50, 50, "Cut"); } } else { context.Response.Write("0"); } } catch { context.Response.Write("0"); } }
protected void btnCargaExcel_Click(object sender, EventArgs e) { HttpPostedFile filePosted = Request.Files[0]; string pathArchivo = "c:\\KeyWeb_Log\\excelTempCC.xlsx"; filePosted.SaveAs(pathArchivo); var excelFile = new ExcelQueryFactory(pathArchivo); var miHoja = excelFile.Worksheet(0).Select(x => x).ToList(); CN_CatCNac_Estructura cm_Estr = new CN_CatCNac_Estructura(model); using (TransactionScope scope = new TransactionScope()) { try { cm_Estr.Borrar(Int32.Parse(Request.QueryString["Id"])); listEstructura.Clear(); int padre1 = 0; int padre2 = 0; int padre3 = 0; int padre4 = 0; foreach (var item in miHoja) { CatCNac_Estructura est = new CatCNac_Estructura(); est.Id_Matriz = Int32.Parse(Request.QueryString["Id"]); //Nivel 1 if (item["Nivel ACYS"] == null) { throw new Exception("Falta la columna Nivel ACYS"); } if (item["ACYS"] == null) { throw new Exception("Falta la columna ACYS"); } if (item["Sucursal"] == null) { throw new Exception("Falta la columna Sucursal"); } if (nivelMax >= 1) { est.NombreNodo = item[0].Value.ToString(); if (!this.listEstructura.Exists(x => x.NombreNodo == est.NombreNodo && x.Id_Matriz == est.Id_Matriz && x.Nivel == 1)) { est.Nivel = 1; est.NodoPadre = 0; if (nivelMax == 1) { est.Nivel_ACYS = item["Nivel ACYS"].Cast <int>(); var acysC = listaACYS.Where(x => x.Nombre == item["ACYS"]).FirstOrDefault(); if (acysC == null) { throw new Exception("El acys no existe: " + item["ACYS"]); } int idAcys = acysC.Id; est.id_Acys = idAcys; est.Sucursal = item["Sucursal"].Cast <int>(); var suc = listaSucursales.Where(x => x.Id_Cd == est.Sucursal).FirstOrDefault(); if (suc == null) { throw new Exception("La Sucursal no existe: " + item["Sucursal"]); } est.NombreSucursal = item["Sucursal"] + " - " + suc.Cd_Nombre; } int resId = cm_Estr.Alta(est); est.Id = resId; padre1 = resId; listEstructura.Add(est); } } if (nivelMax >= 2) { //Nivel 2 est = new CatCNac_Estructura(); est.NombreNodo = item[1].Value.ToString(); est.Id_Matriz = Int32.Parse(Request.QueryString["Id"]); if (!this.listEstructura.Exists(x => x.NombreNodo == est.NombreNodo && x.Id_Matriz == est.Id_Matriz && x.Nivel == 2 && x.NodoPadre == padre1)) { est.Id_Matriz = Int32.Parse(Request.QueryString["Id"]); est.Nivel = 2; est.NodoPadre = padre1; if (nivelMax == 2) { est.Nivel_ACYS = item["Nivel ACYS"].Cast <int>(); var acysC = listaACYS.Where(x => x.Nombre == item["ACYS"]).FirstOrDefault(); if (acysC == null) { throw new Exception("El acys no existe: " + item["ACYS"]); } int idAcys = acysC.Id; est.id_Acys = idAcys; est.Sucursal = item["Sucursal"].Cast <int>(); var suc = listaSucursales.Where(x => x.Id_Cd == est.Sucursal).FirstOrDefault(); if (suc == null) { throw new Exception("La Sucursal no existe: " + item["Sucursal"]); } est.NombreSucursal = item["Sucursal"] + " - " + suc.Cd_Nombre; } int resId = cm_Estr.Alta(est); est.Id = resId; padre2 = resId; listEstructura.Add(est); } } if (nivelMax >= 3) { //Nivel 3 est = new CatCNac_Estructura(); est.NombreNodo = item[2].Value.ToString(); est.Id_Matriz = Int32.Parse(Request.QueryString["Id"]); if (!this.listEstructura.Exists(x => x.NombreNodo == est.NombreNodo && x.Id_Matriz == est.Id_Matriz && x.Nivel == 3 && x.NodoPadre == padre2)) { est.Id_Matriz = Int32.Parse(Request.QueryString["Id"]); est.Nivel = 3; est.NodoPadre = padre2; if (nivelMax == 3) { est.Nivel_ACYS = item["Nivel ACYS"].Cast <int>(); var acysC = listaACYS.Where(x => x.Nombre == item["ACYS"]).FirstOrDefault(); if (acysC == null) { throw new Exception("El acys no existe: " + item["ACYS"]); } int idAcys = acysC.Id; est.id_Acys = idAcys; est.Sucursal = item["Sucursal"].Cast <int>(); var suc = listaSucursales.Where(x => x.Id_Cd == est.Sucursal).FirstOrDefault(); if (suc == null) { throw new Exception("La Sucursal no existe: " + item["Sucursal"]); } est.NombreSucursal = item["Sucursal"] + " - " + suc.Cd_Nombre; } int resId = cm_Estr.Alta(est); est.Id = resId; padre3 = resId; listEstructura.Add(est); } } if (nivelMax >= 4) { //Nivel 4 est = new CatCNac_Estructura(); est.NombreNodo = item[3].Value.ToString(); est.Id_Matriz = Int32.Parse(Request.QueryString["Id"]); if (!this.listEstructura.Exists(x => x.NombreNodo == est.NombreNodo && x.Id_Matriz == est.Id_Matriz && x.Nivel == 4 && x.NodoPadre == padre3)) { est.Id_Matriz = Int32.Parse(Request.QueryString["Id"]); est.Nivel = 4; est.NodoPadre = padre3; est.Nivel_ACYS = item["Nivel ACYS"].Cast <int>(); var acysC = listaACYS.Where(x => x.Nombre == item["ACYS"]).FirstOrDefault(); if (acysC == null) { throw new Exception("El acys no existe: " + item["ACYS"]); } int idAcys = acysC.Id; est.id_Acys = idAcys; est.Sucursal = item["Sucursal"].Cast <int>(); var suc = listaSucursales.Where(x => x.Id_Cd == est.Sucursal).FirstOrDefault(); if (suc == null) { throw new Exception("La Sucursal no existe: " + item["Sucursal"]); } est.NombreSucursal = item["Sucursal"] + " - " + suc.Cd_Nombre; int resId = cm_Estr.Alta(est); est.Id = resId; padre4 = resId; listEstructura.Add(est); } } } model.SaveChanges(); scope.Complete(); } catch (Exception ex) { scope.Dispose(); listEstructura.Clear(); listEstructura = cm_Estr.ConsultarTodos(Int32.Parse(Request.QueryString["Id"])); RAM1.ResponseScripts.Add("CloseAlert('" + ex.Message + "')"); } finally { var nodoA = treeEstructura.Nodes[0]; var hijosPrimerNodo = listEstructura.Where(x => x.Nivel == 1).ToList(); nodoA.Nodes.Clear(); ConstruirEstructura(ref nodoA, hijosPrimerNodo); AgregarControles(ref nodoA, hijosPrimerNodo, null); treeEstructura.ExpandAllNodes(); } } }
protected void Page_Command(Object sender, CommandEventArgs e) { if (e.CommandName == "Next") { if (Page.IsValid) { try { HttpPostedFile pstIMPORT = fileIMPORT.PostedFile; if (pstIMPORT != null) { if (pstIMPORT.FileName.Length > 0) { string sFILENAME = Path.GetFileName(pstIMPORT.FileName); string sFILE_EXT = Path.GetExtension(sFILENAME); string sFILE_MIME_TYPE = pstIMPORT.ContentType; if (sFILE_MIME_TYPE == "text/xml") { using (MemoryStream mstm = new MemoryStream()) { using (BinaryWriter mwtr = new BinaryWriter(mstm)) { using (BinaryReader reader = new BinaryReader(pstIMPORT.InputStream)) { byte[] binBYTES = reader.ReadBytes(8 * 1024); while (binBYTES.Length > 0) { for (int i = 0; i < binBYTES.Length; i++) { // MySQL dump seems to dump binary 0 & 1 for byte values. if (binBYTES[i] == 0) { mstm.WriteByte(Convert.ToByte('0')); } else if (binBYTES[i] == 1) { mstm.WriteByte(Convert.ToByte('1')); } else { mstm.WriteByte(binBYTES[i]); } } binBYTES = reader.ReadBytes(8 * 1024); } } mwtr.Flush(); mstm.Seek(0, SeekOrigin.Begin); XmlDocument xml = new XmlDocument(); xml.Load(mstm); try { // 09/30/2006 Paul. Clear any previous error. lblImportErrors.Text = ""; SplendidImport.Import(xml, null, chkTruncate.Checked); } catch (Exception ex) { lblImportErrors.Text = ex.Message; } } } } else { throw(new Exception("XML is the only supported format at this time.")); } } } } catch (Exception ex) { SplendidError.SystemError(new StackTrace(true).GetFrame(0), ex); lblError.Text = ex.Message; return; } } } else if (e.CommandName == "Back") { } }
protected void add(object sender, EventArgs e) { HttpPostedFile postedFile = FileUpload1.PostedFile; string filename1 = Path.GetFileName(postedFile.FileName); HttpPostedFile postedFile11 = FileUpload.PostedFile; string filename11 = Path.GetFileName(postedFile.FileName); if (pdesTxt.Text != "" && addtxt.Text != "" && beds.Text != "" && baths.Text != "" && garage.Text != "" && kitchen.Text != "" && balcony.Text != "" && area.Text != "" && price.Text != "" && filename1 != "" && filename11 != "" && featuresTxt.Text != "" && videolink.Text != "") { SqlCommand cmd = new SqlCommand("insert into tblAdds (userId,lat,lng,pp,pt,sc,sco,proty,expdate,postdate,des,address,bed,bath,garage,kitchen,balconey,sq,price,cover,features,videolink,approved) values (@userId,@lat,@lng,@pp,@pt,@sc,@sco,@proty,@expdate,@postdate,@des,@address,@bed,@bath,@garage,@kitchen,@balconey,@sq,@price,@cover,@features,@videolink,@approved) SELECT propertyId FROM tblAdds WHERE propertyId = SCOPE_IDENTITY()", con); cmd.Parameters.AddWithValue("@userId", Convert.ToInt32(Session["id"].ToString())); cmd.Parameters.AddWithValue("@lat", lat.Text); cmd.Parameters.AddWithValue("@lng", lng.Text); cmd.Parameters.AddWithValue("@pp", ddpurpose.SelectedItem.ToString()); cmd.Parameters.AddWithValue("@pt", ddtype.SelectedItem.ToString()); cmd.Parameters.AddWithValue("@sc", ddcities.SelectedItem.ToString()); cmd.Parameters.AddWithValue("@sco", countryTxt.Text); cmd.Parameters.AddWithValue("@proty", typeaddTxt.Text); cmd.Parameters.AddWithValue("@expdate", DateTime.Now); cmd.Parameters.AddWithValue("@postdate", DateTime.Now); cmd.Parameters.AddWithValue("@des", pdesTxt.Text); cmd.Parameters.AddWithValue("@address", addtxt.Text); cmd.Parameters.AddWithValue("@bed", beds.Text); cmd.Parameters.AddWithValue("@bath", baths.Text); cmd.Parameters.AddWithValue("@garage", garage.Text); cmd.Parameters.AddWithValue("@kitchen", kitchen.Text); cmd.Parameters.AddWithValue("@balconey", balcony.Text); cmd.Parameters.AddWithValue("@sq", area.Text); cmd.Parameters.AddWithValue("@price", price.Text); string filename = Path.GetFileName(postedFile11.FileName); string fileExtension = Path.GetExtension(filename); Stream stream = postedFile11.InputStream; BinaryReader binaryReader = new BinaryReader(stream); Byte[] bytes = binaryReader.ReadBytes((int)stream.Length); cmd.Parameters.AddWithValue("@cover", bytes); cmd.Parameters.AddWithValue("@features", featuresTxt.Text); cmd.Parameters.AddWithValue("@videolink", videolink.Text); cmd.Parameters.AddWithValue("@approved", "false"); SqlDataAdapter sda = new SqlDataAdapter(cmd); DataTable dt = new DataTable(); sda.Fill(dt); addImage(Convert.ToInt32(dt.Rows[0][0])); diamondAddupdate(Convert.ToInt32(Session["id"].ToString())); expire(Convert.ToInt32(dt.Rows[0][0])); Response.Write("<script type=\"text/javascript\">alert('Your Add Posted Waiting 4 Approval');location.href='userDashboard.aspx'</script>"); Session["lat"] = null; Session["lng"] = null; Session["add"] = null; } else { Response.Write("<script>alert('Missing Data')</script>"); } }
protected override void OnLoad(EventArgs e) { HttpPostedFile file = base.Request.Files["NewFile"]; string str = Path.GetExtension(file.FileName).ToLower(); string uploaderType = base.Request.Form["UploaderType"]; bool flag = DataConverter.CBoolean(base.Request.Form["IsWatermark"]); bool flag2 = DataConverter.CBoolean(base.Request.Form["IsThumb"]); int modelId = DataConverter.CLng(base.Request.Form["ModelId"]); string str3 = DataSecurity.FilterBadChar(base.Request.Form["FieldName"]); string allowSuffix = ""; int uploadFileMaxSize = 0; int uploadSize = 0; string customMsg = "请检查网站信息配置是否设置允许的上传文件大小!"; if (!SiteConfig.SiteOption.EnableUploadFiles) { this.SendResults(0xcc); } else { if (!PEContext.Current.Admin.Identity.IsAuthenticated) { if (!PEContext.Current.User.Identity.IsAuthenticated) { UserGroupsInfo userGroupById = UserGroups.GetUserGroupById(-2); if (string.IsNullOrEmpty(userGroupById.GroupSetting)) { this.SendResults(1, "", "", "匿名会员组不存在!"); return; } UserPurviewInfo groupSetting = UserGroups.GetGroupSetting(userGroupById.GroupSetting); if (groupSetting.IsNull) { this.SendResults(1, "", "", "匿名会员组没有进行权限设置!"); return; } if (!groupSetting.EnableUpload) { this.SendResults(1, "", "", "匿名会员组没有开启上传权限!"); return; } uploadSize = groupSetting.UploadSize; } else { if (!PEContext.Current.User.UserInfo.UserPurview.EnableUpload) { this.SendResults(1, "", "", "所属会员组没有开启上传权限!"); return; } uploadSize = PEContext.Current.User.UserInfo.UserPurview.UploadSize; } } if ((file == null) || (file.ContentLength == 0)) { this.SendResults(0xca); } else { if ((modelId == 0) || string.IsNullOrEmpty(str3)) { if (!ConfigurationManager.AppSettings["EasyOne:DefaultUploadSuffix"].ToLower().Contains(str)) { this.SendResults(1, "", "", "不允许上传动态页文件!"); return; } uploadFileMaxSize = SiteConfig.SiteOption.UploadFileMaxSize; } else { IList <FieldInfo> fieldListByModelId = ModelManager.GetFieldListByModelId(modelId); if ((fieldListByModelId != null) && (fieldListByModelId.Count > 0)) { foreach (FieldInfo info3 in fieldListByModelId) { if (string.CompareOrdinal(info3.FieldName, str3) == 0) { allowSuffix = GetAllowSuffix(info3, uploaderType); if (info3.Settings.Count > 7) { uploadFileMaxSize = DataConverter.CLng(info3.Settings[7]); } break; } } } if (string.IsNullOrEmpty(allowSuffix)) { this.SendResults(1, "", "", "字段内容控件没有填写允许上传的后缀!"); return; } if (!allowSuffix.Contains(str.Replace(".", ""))) { this.SendResults(1, "", "", "这种文件类型不允许上传!只允许上传这几种文件类型:" + allowSuffix); return; } customMsg = "请检查所属字段控件是否设置了允许上传文件大小!"; } if (uploadFileMaxSize <= 0) { this.SendResults(1, "", "", customMsg); } else { if (!PEContext.Current.Admin.Identity.IsAuthenticated && (uploadFileMaxSize > uploadSize)) { uploadFileMaxSize = uploadSize; } if (file.ContentLength > (uploadFileMaxSize * 0x400)) { this.SendResults(1, "", "", "请上传小于" + uploadFileMaxSize.ToString() + "KB的文件!"); } else { string str9; int errorNumber = 0; string fileUrl = ""; string str7 = DataSecurity.MakeFileRndName(); string str8 = str7 + str; int num5 = 0; while (true) { str9 = Path.Combine(base.UserFilesDirectory, str8); if (!File.Exists(str9)) { break; } num5++; str8 = string.Concat(new object[] { Path.GetFileNameWithoutExtension(file.FileName), "(", num5, ")", Path.GetExtension(file.FileName) }); errorNumber = 0xc9; } file.SaveAs(str9); fileUrl = base.UserFilesPath + str8; if (!string.IsNullOrEmpty(uploaderType) && (string.CompareOrdinal(uploaderType, "Photo") == 0)) { string oldValue = ""; if (base.Request.ApplicationPath.EndsWith("/", StringComparison.Ordinal)) { oldValue = ("/" + SiteConfig.SiteOption.UploadDir + "/").Replace("//", "/"); } else { oldValue = base.Request.ApplicationPath + "/" + SiteConfig.SiteOption.UploadDir; } if (flag2) { string str11 = base.UserFilesPath + str7 + "_S" + str; Thumbs.GetThumbsPath(fileUrl.Replace(oldValue, ""), str11.Replace(oldValue, "")); } if (flag) { WaterMark.AddWaterMark(fileUrl.Replace(oldValue, "")); } } this.SendResults(errorNumber, fileUrl, str8); } } } } }
public IHttpActionResult UpdateDocument() { try { int documentID = Convert.ToInt32(HttpContext.Current.Request.Form["documentID"]); int insSubClassID = Convert.ToInt32(HttpContext.Current.Request.Form["insSubClassID"]); string description = HttpContext.Current.Request.Form["description"]; int userID = Convert.ToInt32(HttpContext.Current.Request.Form["userID"]); DocumentVM existingDocument = manageDocument.GetDocumentByID(documentID); string documentName = string.Empty; HttpPostedFile uploadedDocument = null; string newDocument = string.Empty; string newDocumentURL = string.Empty; DocumentVM documentVM = new DocumentVM(); documentVM.DocumentID = documentID; documentVM.InsuranceSubClassID = insSubClassID; documentVM.Description = description; documentVM.ModifiedBy = userID; if (HttpContext.Current.Request.Files.Count > 0) { documentName = HttpContext.Current.Request.Form["documentName"] + "_" + DateTime.Now.ToString("yyyyMMddHHmmss"); uploadedDocument = HttpContext.Current.Request.Files[0]; newDocument = System.Web.Hosting.HostingEnvironment.MapPath("~/Uploads/Documents/") + documentName + Path.GetExtension(uploadedDocument.FileName); newDocumentURL = Request.RequestUri.Scheme + "://" + Request.RequestUri.Authority + "/Uploads/Documents/" + documentName + Path.GetExtension(uploadedDocument.FileName); documentVM.DocumentPath = newDocumentURL; bool status = manageDocument.UpdateDocument(documentVM); if (status) { //Save new file in the directory uploadedDocument.SaveAs(newDocument); //Delete existing file from the directory string[] filePathItemArray = existingDocument.DocumentPath.Split('/'); string existingFileName = filePathItemArray[filePathItemArray.Length - 1]; File.Delete(System.Web.Hosting.HostingEnvironment.MapPath("~/Uploads/Documents/" + existingFileName)); return(Json(new { status = true, message = "Successfully Updated", data = documentVM.DocumentPath })); } else { return(Json(new { status = false, message = "Update Failed" })); } } else { documentVM.DocumentPath = existingDocument.DocumentPath; bool status = manageDocument.UpdateDocument(documentVM); if (status) { return(Json(new { status = true, message = "Successfully Updated", data = documentVM.DocumentPath })); } else { return(Json(new { status = false, message = "Update Failed" })); } } } catch (Exception ex) { return(Json(new { status = false, message = "Unknown error occurred" })); } }
public void btnUpload_Click(object sender, EventArgs e) { this.Grid1.DataSource = ImportDataView = null;// BLL.Globals.GetNullTable(this.Grid1); this.Grid1.DataBind(); this.btnImport.Enabled = false; string fullfile = ""; // 上传文件 try { HttpPostedFile f = this.fudExcel2.PostedFile; string filename = this.fudExcel2.ShortFileName.ToLower(); if (String.IsNullOrEmpty(filename)) { FUI.Alert.Show/*Alert.ShowInParent*/ ("请先选择上传文件 !", "上传提示", FUI.MessageBoxIcon.Warning); return; } if (!filename.EndsWith(".xls") && !filename.EndsWith(".xlsx")) { FUI.Alert.Show/*Alert.ShowInParent*/ ("数据文件必须为 Excel 97-2003 格式 !", "上传提示", FUI.MessageBoxIcon.Warning); return; } string path = Server.MapPath("~/Uploads/Excel/"); fullfile = path + String.Format("upexcel_{0}", filename); f.SaveAs(fullfile); } catch (Exception err) { FUI.Alert.Show/*Alert.ShowInParent*/ (err.Message, "上传数据文件失败", FUI.MessageBoxIcon.Error); return; } // 读取文件 DataTable dt = null; try { dt = GetExcelData(fullfile); } catch (Exception err) { FUI.Alert.Show/*Alert.ShowInParent*/ (err.Message, "读取数据文件失败", FUI.MessageBoxIcon.Error); return; } // 检查文件字段 if (!CheckData(dt)) { return; } // 显示在Grid里 ImportDataView = dt.DefaultView; DataView dv = ImportDataView; this.Grid1.PageSize = dv.Count; this.Grid1.DataSource = dv; this.Grid1.DataBind(); this.btnImport.Enabled = true; }
public void PostImportExcel() { string _fileExt = string.Empty; int _code = 0; string _message = string.Empty; try { HttpPostedFile _uploadFiles = Request.Files["uploadFile"] as HttpPostedFile; if (_uploadFiles == null || _uploadFiles.FileName.Length < 3) { _message = "您没有选择要上传的文件!"; _code = -4; } else { _fileExt = Path.GetExtension(_uploadFiles.FileName).ToLower(); //获取文件扩展名 String[] _allowedExt = { ".xls", ".xlsx" }; //允许上传的文件格式 if (!_allowedExt.Contains(_fileExt)) { _message = "您上传的格式为" + _fileExt + ", 本统只接受扩展名为" + string.Join("、", _allowedExt) + "格式文件"; _code = -3; } else if (_uploadFiles.ContentLength == 0) { _message = "上传的内容为空!"; _code = -2; } else if (_uploadFiles.ContentLength > 1024 * 1024 * 8) { _message = "您上传的文件超过了8M!"; _code = -1; } } if (_code == 0) { string _fileName = ShortFileNameUtil.ShortFileName(Guid.NewGuid().ToString()) + _fileExt; string _virtualPath = "/UploadFiles/employeeXls/"; string _physicalPath = HttpContext.Server.MapPath(_virtualPath); if (!Directory.Exists(_physicalPath)) { Directory.CreateDirectory(_physicalPath); } string _fullPath = _physicalPath + _fileName; _uploadFiles.SaveAs(_fullPath); DataTable _employeeData = JNyuluUtils.ImportExcel(_fullPath); int _i = 0; StringBuilder _result = new StringBuilder(); _result.AppendLine("上传路径为:" + _virtualPath + _fileName); _result.AppendLine("Excel解析日志记录:"); foreach (DataRow dr in _employeeData.Rows) { _i++; try { //["学籍号"] dr["学生姓名"] dr["家长手机"] dr["家庭电话"] dr["备注"] string _name = dr["学籍号"].ToString() + ""; if (!string.IsNullOrEmpty(_name)) { Employee _employee = _employeeService.GetEmployeeByName(_name); if (_employee == null) { _employee = new Employee(); _employee.UserType = 0; _employee.Name = _name; _employee.TrueName = dr["学生姓名"].ToString() + ""; string _phone = dr["家庭电话"].ToString() + ""; if (_phone.IndexOf("e+") > 0) { _phone = (double.Parse(_phone)).ToString(); } _employee.Phone = _phone; LogHelper.Info(dr["家长手机"].GetType().ToString() + " " + dr["家长手机"]); string _mobile = dr["家长手机"].ToString() + ""; if (_mobile.IndexOf("e+") > 0) { _mobile = (double.Parse(_mobile)).ToString(); } _employee.Mobile = _mobile; _employee.PassWord = _mobile; //初始密码设为用户的手机号 _employee.Permission = 0; _employee.ID = _employeeService.InsertEmployee(_employee); } } else { LogHelper.Error("记录[" + _i + "] 中的学籍号不能为空"); _result.AppendLine("记录[" + _i + "] 中的学籍号不能为空"); } } catch (Exception ex) { LogHelper.Error("记录[" + _i + "]导入出错 " + ex.ToString()); _result.AppendLine("记录[" + _i + "]导入出错 " + ex.ToString()); continue; } _i++; } _message = _result.ToString(); } } catch (Exception ex) { _code = -1; _message = ex.Message; } finally { RenderText("{code: " + _code + ",message: \"" + _message.Replace(@"\", @"\\") + "\"}"); CancelLayout(); } }
public void submitCustomerInfo() { VerifySignCheck(); try { int storeId = prams.Value <int>("storeId"); string name = prams.Value <string>("name"); string mobile = prams.Value <string>("mobile"); string token = prams.Value <string>("token"); int type = prams.Value <int>("type"); if (string.IsNullOrEmpty(name)) { result.setResult(ApiStatusCode.参数错误, "客户名称不能为空"); goto Finish; } if (string.IsNullOrEmpty(mobile)) { result.setResult(ApiStatusCode.参数错误, "客户联系不能为空"); goto Finish; } if (!RegexHelper.IsValidRealMobileNo(mobile)) { result.setResult(ApiStatusCode.参数错误, "非法的手机号码"); goto Finish; } string imgContent = ""; //上传图片 for (int i = 0; i < Context.Request.Files.Count; i++) { HttpPostedFile oFile = Context.Request.Files[i]; if (oFile == null) { continue; } string fileName = "/resource/modeng/" + System.DateTime.Now.ToString("yyyyMMddHHmmss") + StringHelper.CreateCheckCodeWithNum(6) + ".jpg"; if (FileUploadHelper.UploadFile(oFile, fileName)) { if (string.IsNullOrEmpty(imgContent)) { imgContent = fileName; } else { imgContent += "|" + fileName; } } } int flag = UserCarLogic.Instance.AddCustomerModel(new CustomerModel() { UserId = storeId, UserName = name, UserMobile = mobile, UserImg = imgContent, UserToken = string.IsNullOrEmpty(token) ? "" : token, UserType = type }); if (flag > 0) { result.setResult(ApiStatusCode.OK, flag); } else { result.setResult(ApiStatusCode.失败, ""); } } catch (Exception ex) { LogHelper.Debug(string.Format("StackTrace:{0},Message:{1}", ex.StackTrace, ex.Message), this.DebugMode); result.setResult(ApiStatusCode.务器错误, ex.Message); } goto Finish; Finish: JsonResult(result); }
void SaveFile(HttpPostedFile file) { // Specify the path to save the uploaded file to. savePath = Server.MapPath("Images"); // Get the name of the file to upload. string fileName = fuPhoto.FileName; // Create the path and file name to check for duplicates. string pathToCheck = Path.Combine(savePath, fileName); // Create a temporary file name to use for checking duplicates. string tempfileName = ""; // Check to see if a file already exists with the // same name as the file to upload. if (System.IO.File.Exists(pathToCheck)) { int counter = 2; while (System.IO.File.Exists(pathToCheck) == true) { // if a file with this name already exists, // prefix the filename with a number. tempfileName = counter.ToString() + fileName; pathToCheck = Path.Combine(savePath, tempfileName); counter++; } fileName = tempfileName; // Notify the user that the file name was changed. lblMessage.Text = "A file with the same name already exists." + "<br />Your file was saved as " + fileName; // Append the name of the file to upload to the path. savePath = Path.Combine(savePath, fileName); // Call the SaveAs method to save the uploaded // file to the specified directory. fuPhoto.SaveAs(savePath); Book book = new Book(); book.PhotoName = savePath; User user = new User(); user = (User)Session["User"]; book.Title = txtTitle.Text; book.Price = txtPrice.Text; book.BookTypeID = new Guid(ddlGenre.SelectedValue); user.Books.List.Add(book); user.Save(); } else { // Append the name of the file to upload to the path. savePath = Path.Combine(savePath, fileName); // Call the SaveAs method to save the uploaded // file to the specified directory. fuPhoto.SaveAs(savePath); ////XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX Book book = new Book(); book.PhotoName = savePath; User user = new User(); user = (User)Session["User"]; book.Title = txtTitle.Text; book.Price = txtPrice.Text; book.BookTypeID = new Guid(ddlGenre.SelectedValue); user.Books.List.Add(book); user.Save(); // Notify the user that the file was saved successfully. lblMessage.Text = "Your file was uploaded successfully."; //Response.Redirect("UploadPhoto.aspx"); } }
/// <summary> /// 重点在于要给合同文本内容赋值BC_CONTEXT /// </summary> private void UpFile() { //获取文件保存的路径 // @"F:\质量部附件\" + Convert.ToString(System.DateTime.Now.Year) string FilePath = @"F:\质量管理附件\" + Convert.ToString(System.DateTime.Now.Year); if (!Directory.Exists(FilePath)) { Directory.CreateDirectory(FilePath); } // //对客户端已上载的单独文件的访问 HttpPostedFile UserHPF = FileUpload1.PostedFile; try { string fileContentType = UserHPF.ContentType; // 获取客户端发送的文件的 MIME 内容类型 if (fileContentType == "application/vnd.ms-excel" || fileContentType == "application/msword" || fileContentType == "application/pdf" || fileContentType == "application/octet-stream" || fileContentType == "application/vnd.openxmlformats-officedocument.wordprocessingml.document" || fileContentType == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") //传送文件类型 { if (UserHPF.ContentLength > 0) { //调用GetAutoID方法获取上传文件自动编号 //int IntFieldID = CC.GetAutoID("fileID", "tb_files"); //文件的真实名(格式:[文件编号]上传文件名) //用于实现上传多个相同文件时,原有文件不被覆盖 string strFileTName = System.IO.Path.GetFileName(UserHPF.FileName); if (!File.Exists(FilePath + "//" + strFileTName)) { //定义插入字符串,将上传文件信息保存在数据库中 string sqlStr = "insert into TBQC_FILES(BC_CONTEXT,fileLoad,fileUpDate,fileName)"; sqlStr += "values('" + HiddenFieldContent.Value + "'"; sqlStr += ",'" + FilePath + "'"; sqlStr += ",'" + DateTime.Now.ToLongDateString() + "'"; sqlStr += ",'" + strFileTName + "')"; //打开与数据库的连接 DBCallCommon.ExeSqlText(sqlStr); //将上传的文件存放在指定的文件夹中 UserHPF.SaveAs(FilePath + "//" + strFileTName); IntIsUF = 1; filename.Text = strFileTName;//显示文件名 } else { filesError.Visible = true; filesError.Text = "文件名与服务器某个合同名重名,请您核对后重新上传!"; IntIsUF = 1; } } } else { filesError.Visible = true; filesError.Text = "文件类型不符合要求,请您核对后重新上传!"; IntIsUF = 1; } } catch { filesError.Text = "文件上传过程中出现错误!"; filesError.Visible = true; return; } if (IntIsUF == 1) { IntIsUF = 0; } else { filesError.Visible = true; filesError.Text = "请选择上传文件!"; } }
/// <summary> /// Processes the content file. /// </summary> /// <param name="context">The context.</param> /// <param name="uploadedFile">The uploaded file.</param> private void ProcessContentFile(HttpContext context, HttpPostedFile uploadedFile) { // validate file type (child FileUploader classes, like ImageUploader, can do additional validation); this.ValidateFileType(context, uploadedFile); // NEVER TRUST THE CLIENT!!!! string untrustedFileName = uploadedFile.FileName; string untrustedFolderPath = context.Request.Form["folderPath"] ?? string.Empty; string encryptedRootFolder = context.Request.QueryString["rootFolder"]; /* Scrub the file name */ string scrubedFileName = ScrubFileName(untrustedFileName); if (string.IsNullOrWhiteSpace(scrubedFileName)) { throw new Rock.Web.FileUploadException("Invalid File Name", System.Net.HttpStatusCode.BadRequest); } /* Scrub the folder path */ string scrubedFolderPath = ScrubFilePath(untrustedFolderPath); /* Determine the root upload folder */ string trustedRootFolder = string.Empty; // If a rootFolder was specified in the URL, try decrypting it (It is encrypted to help prevent direct access to filesystem). if (!string.IsNullOrWhiteSpace(encryptedRootFolder)) { trustedRootFolder = Encryption.DecryptString(encryptedRootFolder); } // If we don't have a rootFolder, default to the ~/Content folder. if (string.IsNullOrWhiteSpace(trustedRootFolder)) { trustedRootFolder = "~/Content"; } /* Combine the root and folder paths to get the real physical location */ // Get the absolute path for our trusted root. string trustedPhysicalRootFolder = Path.GetFullPath(context.Request.MapPath(trustedRootFolder)); // Treat rooted folder paths as relative string untrustedRelativeFolderPath = ""; if (!string.IsNullOrWhiteSpace(scrubedFolderPath)) { untrustedRelativeFolderPath = scrubedFolderPath.TrimStart(Path.GetPathRoot(scrubedFolderPath).ToCharArray()); } // Get the absolute path for our untrusted folder. string untrustedPhysicalFolderPath = Path.GetFullPath(Path.Combine(trustedPhysicalRootFolder, untrustedRelativeFolderPath)); /* Make sure the physical location is valid */ // Make sure the untrusted folder is inside our trusted root folder. string trustedPhysicalFolderPath = string.Empty; if (untrustedPhysicalFolderPath.StartsWith(trustedPhysicalRootFolder)) { // If so, then we can trust it. trustedPhysicalFolderPath = untrustedPhysicalFolderPath; } else { // Otherwise, something's fishy throw new Rock.Web.FileUploadException("Invalid folderPath", System.Net.HttpStatusCode.BadRequest); } // Yay! We now have a trusted physical path and a safe filename // Let's put those together and upload our file string physicalFilePath = Path.Combine(trustedPhysicalFolderPath, scrubedFileName); // Make sure the physical path exists if (!Directory.Exists(trustedPhysicalFolderPath)) { Directory.CreateDirectory(trustedPhysicalFolderPath); } // If the file already exists, bail if (File.Exists(physicalFilePath)) { throw new Rock.Web.FileUploadException("File already exists", System.Net.HttpStatusCode.BadRequest); } // Get the file contents var fileContent = GetFileContentStream(context, uploadedFile); // Write it out to the response using (var writeStream = File.OpenWrite(physicalFilePath)) { if (fileContent.CanSeek) { fileContent.Seek(0, SeekOrigin.Begin); } fileContent.CopyTo(writeStream); } var response = new { Id = string.Empty, FileName = Path.Combine(untrustedRelativeFolderPath, scrubedFileName) }; context.Response.Write(response.ToJson()); }
/// <summary> /// Adiciona o arquivo para a coleção. /// </summary> /// <param name="name"></param> /// <param name="httpPostedFile"></param> internal void AddFile(string name, HttpPostedFile httpPostedFile) { BaseAdd(name, httpPostedFile); }
private void PostBack() { string cPath = curPath + "\\"; try { if (Request.Form["txtFolderName"] != null) { #region Создать папку if (Request.Form["txtFolderName"].Trim().Length > 0) { if(!Directory.Exists((cPath + Request.Form["txtFolderName"]))) { Directory.CreateDirectory((cPath + Request.Form["txtFolderName"])); } } #endregion } else if (Request.Files.Count > 0) { if (Request.Form["hReplace"] == null) { #region Загрузка архива HttpPostedFile pf = Request.Files[0]; if (pf.FileName.Length > 0) { using (ZipInputStream s = new ZipInputStream(pf.InputStream)) { ZipEntry theEntry; while ((theEntry = s.GetNextEntry()) != null) { string directoryName = Request.MapPath(sCurPath + "/" + Path.GetDirectoryName(theEntry.Name)); string fileName = Path.GetFileName(theEntry.Name); //Hashtable ht = new Hashtable(); //ht["name"] = theEntry.Name; //ht["directoryName"] = directoryName; //ht["fileName"] = fileName; //Log.Write("entry", ht); //continue; // create directory if (directoryName.Length > 0) { Directory.CreateDirectory(directoryName); } if (fileName != String.Empty) { using (FileStream streamWriter = File.Create(directoryName + "\\" + fileName)) { int size = 2048; byte[] data = new byte[2048]; while (true) { size = s.Read(data, 0, data.Length); if (size > 0) { streamWriter.Write(data, 0, size); } else { break; } } } } } } } #endregion } else { #region Загрузка файла HttpPostedFile pf = Request.Files[0]; if (pf.FileName.Length > 0) { //получение имени файла string[] af = pf.FileName.Split('\\'); string file = af[af.Length - 1]; //проверка типа файла bool wrongType = false; if (sFilter != "*") { wrongType = true; string[] arFilter = sFilter.ToLower().Split(';'); string ext = this.GetExtention(file).ToLower(); foreach (string fe in arFilter) if (ext == fe) { wrongType = false; break; } } if (!wrongType) { //создание уникального имени if (Request.Form["hReplace"] != "1") { int i = 0; while (File.Exists(cPath + file)) { i++; file = i + file; } } //сохранение pf.SaveAs(cPath + file); } else { throw new Exception("Wrong file type."); } } #endregion } } else if (Request.Form["txtNewName"] != null && Request.Form["txtOldName"] != null && Request.Form["txtPreviewW"] != null && Request.Form["txtPreviewH"] != null) { #region Сохранение с новым размером if (Request.Form["txtNewName"].Trim().Length > 0 && Request.Form["txtOldName"].Trim().Length > 0 && Request.Form["txtPreviewW"].Trim().Length > 0 && Request.Form["txtPreviewH"].Trim().Length > 0 ) { ImageFormat imageFormat = ImageFormat.Png; string sOldFile = Request.Form["txtOldName"].Trim(); string sNewFile = Request.Form["txtNewName"].Trim(); int nWidth = int.Parse(Request.Form["txtPreviewW"]); int nHeigth = int.Parse(Request.Form["txtPreviewH"]); string ext = GetExtention(sNewFile).ToLower(); switch (ext) { case "gif": imageFormat = ImageFormat.Gif; break; case "jpg": case "jpeg": imageFormat = ImageFormat.Jpeg; break; case "png": imageFormat = ImageFormat.Png; break; case "bmp": imageFormat = ImageFormat.Bmp; break; default: sNewFile += ".png"; break; } Bitmap bitmap = null; Image image = null; Graphics gr = null; SmoothingMode sm = (SmoothingMode)Enum.Parse(typeof(SmoothingMode), Request.Form["cmbSmoothingMode"], true); CompositingQuality cq = (CompositingQuality)Enum.Parse(typeof(CompositingQuality), Request.Form["cmbCompositingQuality"], true); try { bitmap = new Bitmap(cPath + sOldFile); image = new Bitmap(nWidth, nHeigth); gr = Graphics.FromImage(image); gr.SmoothingMode = sm; gr.CompositingQuality = cq; gr.DrawImage(bitmap, 0, 0, nWidth, nHeigth); bitmap.Dispose(); gr.Dispose(); while (File.Exists(cPath + sNewFile)) { sNewFile = "0" + sNewFile; } image.Save(cPath + sNewFile, imageFormat); } finally { if (gr != null) gr.Dispose(); if (bitmap != null) bitmap.Dispose(); if (image != null) image.Dispose(); } } #endregion } else if (Request.Form["txtFileName"] != null) { #region Создание файла string file = Request.Form["txtFileName"].Trim(); if (Request.Form["cmbFileType"] == "*") { if(Request.Form["hReplace"]!="1") { int i=0; while (File.Exists(cPath + file)) { i++; file = i + file; } } File.Create(cPath + file).Close(); } else { string content = ""; string cext = Request.Form["cmbFileType"].Split('-')[0]; file = file + "." + cext; if(Request.Form["hReplace"]!="1") { int i=0; while (File.Exists(cPath + file)) { i++; file = i + file; } } DataRow[] rows = tbTemplates.Select("id like '*;" + Request.Form["cmbFileType"] + ";*'"); if (rows.Length > 0) { content = rows[0]["content"].ToString(); } Encoding enc = Encoding.Default; if (IsXmlFile(file)) enc = Encoding.UTF8; StreamWriter sw = null; try { sw = new StreamWriter(cPath + file, false, enc); sw.Write(content); } finally { if (sw != null) sw.Close(); } } #endregion } else if (Request.Form["act"] == "delete") { #region Удаление файла string file = Request.MapPath(Request.Form["hFile"]).ToLower(); if (File.Exists(file)) { bool allowed = false; DataTable tb = Config.GetConfigTable("delete.config","folder"); for(int i=0;i<tb.Rows.Count;i++) { string folder = Request.MapPath(tb.Rows[i]["name"].ToString()).ToLower(); if(file.StartsWith(folder)) { allowed = tb.Rows[i]["allow"].ToString()=="1"; if(!allowed) { break; } } } if(allowed) { File.Delete(file); } else { throw new UnauthorizedAccessException("Удаление запрещено!"); } } #endregion } else if (Request.Form["act"] == "deletefolder") { #region Удаление папки string folder = Request.MapPath(Request.Form["hFolder"]); if (Directory.Exists(folder)) { if(Directory.GetFileSystemEntries(folder).Length>0) { Directory.Delete(folder); } } #endregion } Response.Redirect(Sota.Web.SimpleSite.Path.Full); } catch (Exception ex) { sError = ex.Message; } }
public override void SendResponse(System.Web.HttpResponse response) { int iErrorNumber = 0; string sFileName = ""; string sFilePath = ""; string sUnsafeFileName = ""; try { this.CheckConnector(); this.CheckRequest(); if (!this.CurrentFolder.CheckAcl(AccessControlRules.FileUpload)) { ConnectorException.Throw(Errors.Unauthorized); } HttpPostedFile oFile = null; if (HttpContext.Current.Request.Files["upload"] != null) { oFile = HttpContext.Current.Request.Files["upload"]; } else if (HttpContext.Current.Request.Files["NewFile"] != null) { oFile = HttpContext.Current.Request.Files["NewFile"]; } else if (HttpContext.Current.Request.Files.AllKeys.Length > 0) { oFile = HttpContext.Current.Request.Files[HttpContext.Current.Request.Files.AllKeys[0]]; } if (oFile != null) { int iPathIndex = oFile.FileName.LastIndexOf("\\"); sFileName = (iPathIndex >= 0 && oFile.FileName.Length > 1) ? oFile.FileName.Substring(iPathIndex + 1) : oFile.FileName; if (Config.Current.CheckDoubleExtension) { sFileName = this.CurrentFolder.ResourceTypeInfo.ReplaceInvalidDoubleExtensions(sFileName); } sUnsafeFileName = sFileName; if (Config.Current.DisallowUnsafeCharacters) { sFileName = sFileName.Replace(";", "_"); } // 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 (sFileName != sUnsafeFileName) { iErrorNumber = Errors.UploadedInvalidNameRenamed; } if (Connector.CheckFileName(sFileName) && !Config.Current.CheckIsHiddenFile(sFileName)) { 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(sFileName); 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 = CKFinder.Connector.Util.GetFileNameWithoutExtension(sFileName); string sFullExtension = CKFinder.Connector.Util.GetExtension(sFileName); int iCounter = 0; // System.IO.File.Exists in C# does not return true for protcted files if (Regex.IsMatch(sFileNameNoExt, @"^(AUX|COM\d|CLOCK\$|CON|NUL|PRN|LPT\d)$", RegexOptions.IgnoreCase)) { iCounter++; sFileName = sFileNameNoExt + "(" + iCounter + ")" + sFullExtension; iErrorNumber = Errors.UploadedFileRenamed; } while (true) { sFilePath = System.IO.Path.Combine(sServerDir, sFileName); if (System.IO.File.Exists(sFilePath)) { iCounter++; sFileName = sFileNameNoExt + "(" + iCounter + ")" + sFullExtension; 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 (System.Security.SecurityException) { #if DEBUG throw; #else iErrorNumber = Errors.AccessDenied; #endif } catch (System.UnauthorizedAccessException) { #if DEBUG throw; #else iErrorNumber = Errors.AccessDenied; #endif } catch { #if DEBUG throw; #else iErrorNumber = Errors.Unknown; #endif } #if DEBUG if (iErrorNumber == Errors.None || iErrorNumber == Errors.UploadedFileRenamed || iErrorNumber == Errors.UploadedInvalidNameRenamed) { response.Clear(); } #else response.Clear(); #endif System.Web.HttpRequest _Request = System.Web.HttpContext.Current.Request; if (_Request.QueryString["response_type"] != null && "txt" == _Request.QueryString["response_type"].ToString()) { string _errorMsg = ""; if (iErrorNumber > 0) { _errorMsg = Lang.getErrorMessage(iErrorNumber).Replace("%1", sFileName); if (iErrorNumber != Errors.UploadedFileRenamed && iErrorNumber != Errors.UploadedInvalidNameRenamed) { sFileName = ""; } } response.Write(sFileName + "|" + _errorMsg); } else { response.Write("<script type=\"text/javascript\">"); response.Write(this.GetJavaScriptCode(iErrorNumber, sFileName, this.CurrentFolder.Url)); response.Write("</script>"); } Connector.CKFinderEvent.ActivateEvent(CKFinderEvent.Hooks.AfterFileUpload, this.CurrentFolder, sFilePath); response.End(); }
protected void Page_Load(object sender, EventArgs e) { // System.Drawing.Image thumbnail_image = null;//缩略图 System.Drawing.Image original_image = null; //原图 System.Drawing.Bitmap final_image = null; //最终图片 System.Drawing.Graphics graphic = null; MemoryStream ms = null; try { // Get the data HttpPostedFile jpeg_image_upload = Request.Files["Filedata"]; // Retrieve the uploaded image original_image = System.Drawing.Image.FromStream(jpeg_image_upload.InputStream); int width = original_image.Width; int height = original_image.Height; final_image = new System.Drawing.Bitmap(original_image); graphic = System.Drawing.Graphics.FromImage(final_image); graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; graphic.DrawImage(original_image, 0, 0, width, height); ms = new MemoryStream(); final_image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); string thumbnail_id = DateTime.Now.ToString("yyyyMMddHHmmssfff"); Thumbnail thumb = new Thumbnail(thumbnail_id, ms.GetBuffer()); List <Thumbnail> thumbnails = Session["file_info"] as List <Thumbnail>; if (thumbnails == null) { thumbnails = new List <Thumbnail>(); Session["file_info"] = thumbnails; } thumbnails.Add(thumb); Response.StatusCode = 200; Response.Write(thumbnail_id); } catch (Exception ex) { Response.StatusCode = 500; Response.Write("An error occured"); Response.End(); } finally { // Clean up if (final_image != null) { final_image.Dispose(); } if (graphic != null) { graphic.Dispose(); } if (ms != null) { ms.Close(); } Response.End(); } }
/// <summary> /// 检查每个文件的合法检验 /// </summary> private bool CheckFile(HttpPostedFile file, ref stuUpLoadFile uploadFile, List <stuUpLoadFileType> lstFileType = null) { //获取文件名前缀 var fileNamePrefix = Path.GetFileNameWithoutExtension(file.FileName); //获取文件名后缀 var fileNameExtension = file.FileName.LastIndexOf('.') > -1 ? Path.GetExtension(file.FileName).Substring(1) : Path.GetExtension(file.FileName); //文件容量 var fileContentLength = file.ContentLength / 1024; if (string.IsNullOrWhiteSpace(file.FileName)) { uploadFile.ErrorMessage = "未检测到文件上传!"; return(false); } if (string.IsNullOrWhiteSpace(fileNamePrefix)) { uploadFile.ErrorMessage = "文件: [ " + file.FileName + " ] 前缀名不能为空"; return(false); } if (file.ContentLength > 0 && fileContentLength == 0) { fileContentLength = 1; } if (fileContentLength <= 0) { uploadFile.ErrorMessage = "文件: [ " + file.FileName + " ] 的大小不能为0KB"; return(false); } //循环文件类型,长度 if (lstFileType == null || lstFileType.Count == 0) { return(true); } //true表示属于允许上传的类型 var isfileExtension = false; foreach (var fileType in lstFileType) { //判断文件类型,长度是否允许上传 if (!fileNameExtension.IsEquals(fileType.type)) { continue; } isfileExtension = true; //判断文件容量是否超过上限 if (fileType.size != 0 && fileContentLength > fileType.size) { uploadFile.ErrorMessage = string.Format("文件类型为 [ {0} ] 的容量不能超过: [ {1} KB ]", fileType.type, fileType.size); return(false); } break; } if (!isfileExtension) { uploadFile.ErrorMessage = string.Format("文件扩展名: [ {0} ] 不允许上传", fileNameExtension); return(false); } return(true); }
void PostData() { if (!ValidateData()) { return; } bool bHasVisible = false; //foreach (CBaseObject objCIVD in m_ViewDetail.ColumnInViewDetailMgr.GetList()) foreach (CBaseObject objCol in m_Table.ColumnMgr.GetList()) { //CColumnInViewDetail civd = (CColumnInViewDetail)objCIVD; //CColumn col = (CColumn)m_Table.ColumnMgr.Find(civd.FW_Column_id); CColumn col = (CColumn)objCol; if (col == null) { continue; } //判断禁止和只读权限字段 if (m_sortRestrictColumnAccessType.ContainsKey(col.Id)) { AccessType accessType = m_sortRestrictColumnAccessType[col.Id]; if (accessType == AccessType.forbide) { continue; } //只读只在界面控制,有些默认值需要只读也需要保存数据 //else if (accessType == AccessType.read) // continue; } // if (col.Code.Equals("id", StringComparison.OrdinalIgnoreCase)) { continue; } else if (col.Code.Equals("Created", StringComparison.OrdinalIgnoreCase)) { continue; } else if (col.Code.Equals("Creator", StringComparison.OrdinalIgnoreCase)) { //BaseObject.SetColValue(col, Program.User.Id); continue; } else if (col.Code.Equals("Updated", StringComparison.OrdinalIgnoreCase)) { m_BaseObject.SetColValue(col, DateTime.Now); continue; } else if (col.Code.Equals("Updator", StringComparison.OrdinalIgnoreCase)) { CUser u = (CUser)Session["User"]; m_BaseObject.SetColValue(col, u.Id); continue; } if (col.ColType == ColumnType.object_type) { string ckVal = Request.Params["ckClear_" + col.Code]; if (!string.IsNullOrEmpty(ckVal) && ckVal.ToLower() == "on") { //清空附件 m_BaseObject.SetColValue(col, null); } else { HttpPostedFile postfile = Request.Files.Get("_" + col.Code); if (postfile != null && postfile.ContentLength > 0) { string sFileName = postfile.FileName; if (sFileName.LastIndexOf('\\') > -1)//有些浏览器不带路径 { sFileName = sFileName.Substring(sFileName.LastIndexOf('\\')); } byte[] byteFileName = System.Text.Encoding.Default.GetBytes(sFileName); byte[] byteValue = new byte[254 + postfile.ContentLength]; byte[] byteData = new byte[postfile.ContentLength]; postfile.InputStream.Read(byteData, 0, postfile.ContentLength); Array.Copy(byteFileName, byteValue, byteFileName.Length); Array.Copy(byteData, 0, byteValue, 254, byteData.Length); m_BaseObject.SetColValue(col, byteValue); } } } else if (col.ColType == ColumnType.path_type) { string sUploadPath = col.UploadPath; if (sUploadPath[sUploadPath.Length - 1] != '\\') { sUploadPath += "\\"; } if (!Directory.Exists(sUploadPath)) { Directory.CreateDirectory(sUploadPath); } string ckVal = Request.Params["ckClear_" + col.Code]; if (!string.IsNullOrEmpty(ckVal) && ckVal.ToLower() == "on") { //清空附件 m_BaseObject.SetColValue(col, ""); } else { HttpPostedFile postfile = Request.Files.Get("_" + col.Code); if (postfile != null && postfile.ContentLength > 0) { string sFileName = postfile.FileName; if (sFileName.LastIndexOf('\\') > -1)//有些浏览器不带路径 { sFileName = sFileName.Substring(sFileName.LastIndexOf('\\')); } FileInfo fi = new FileInfo(sUploadPath + sFileName); Guid guid = Guid.NewGuid(); string sDestFile = string.Format("{0}{1}", guid.ToString().Replace("-", ""), fi.Extension); postfile.SaveAs(sUploadPath + sDestFile); string sVal = string.Format("{0}|{1}", sDestFile, sFileName); m_BaseObject.SetColValue(col, sVal); } } } else if (col.ColType == ColumnType.bool_type) { string val = Request.Params["_" + col.Code]; if (!string.IsNullOrEmpty(val) && val.ToLower() == "on") { m_BaseObject.SetColValue(col, true); } else { m_BaseObject.SetColValue(col, false); } } else if (col.ColType == ColumnType.datetime_type) { string val = Request.Params["_" + col.Code]; if (!string.IsNullOrEmpty(val)) { m_BaseObject.SetColValue(col, Convert.ToDateTime(val)); } } else { m_BaseObject.SetColValue(col, Request.Params["_" + col.Code]); } bHasVisible = true; } if (!bHasVisible) { //Response.Write("没有可修改字段!"); Response.Write("<script>alert('没有可修改字段!');</script>"); return; } SortedList <Guid, CBaseObject> arrP = (SortedList <Guid, CBaseObject>)Session["EditMultMasterDetailViewRecord"]; CBaseObject objP = (CBaseObject)arrP.Values[0]; CColumn colP = (CColumn)objP.Table.ColumnMgr.Find(m_ViewDetail.PrimaryKey); CColumn colF = (CColumn)m_Table.ColumnMgr.Find(m_ViewDetail.ForeignKey); m_BaseObject.SetColValue(colF, objP.GetColValue(colP)); CUser user = (CUser)Session["User"]; m_BaseObject.Updator = user.Id; m_BaseObjectMgr.Update(m_BaseObject); if (!m_BaseObjectMgr.Save(true)) { //Response.Write("修改失败!"); Response.Write("<script>alert('修改失败!');</script>"); return; } //在iframe里访问外面,需要parent.parent. //Response.Write("<script>parent.parent.grid.loadData(true);parent.parent.$.ligerDialog.close();</script>"); Response.Write("<script>parent.parent.onOkEditMultDetailRecord2();</script>"); }
public void Upload() { HttpPostedFile hpFile = _FormFile.PostedFile; if (hpFile == null || hpFile.FileName.Trim() == "") { _Error = 1; return; } string Ext = GetExt(hpFile.FileName); if (!IsUpload(Ext)) { _Error = 2; return; } int iLen = hpFile.ContentLength; if (iLen > _MaxSize) { _Error = 3; return; } try { if (!Directory.Exists(_SavePath)) { Directory.CreateDirectory(_SavePath); } byte[] bData = new byte[iLen]; hpFile.InputStream.Read(bData, 0, iLen); string FName; FName = FileName(Ext); string TempFile = ""; if (_IsDraw) { TempFile = FName.Split('.').GetValue(0).ToString() + "_temp." + FName.Split('.').GetValue(1).ToString(); } else { TempFile = FName; } FileStream newFile = new FileStream(_SavePath + TempFile, FileMode.Create); newFile.Write(bData, 0, bData.Length); newFile.Flush(); int _FileSizeTemp = hpFile.ContentLength; string ImageFilePath = _SavePath + FName; if (_IsDraw) { if (_DrawStyle == 0) { System.Drawing.Image Img1 = System.Drawing.Image.FromStream(newFile); Graphics g = Graphics.FromImage(Img1); g.DrawImage(Img1, 100, 100, Img1.Width, Img1.Height); Font f = new Font(_Font, _FontSize); Brush b = new SolidBrush(Color.Red); string addtext = _AddText; g.DrawString(addtext, f, b, _DrawString_x, _DrawString_y); g.Dispose(); Img1.Save(ImageFilePath); Img1.Dispose(); } else { System.Drawing.Image image = System.Drawing.Image.FromStream(newFile); System.Drawing.Image copyImage = System.Drawing.Image.FromFile(_CopyIamgePath); Graphics g = Graphics.FromImage(image); g.DrawImage(copyImage, new Rectangle(image.Width - copyImage.Width - 5, image.Height - copyImage.Height - 5, copyImage.Width, copyImage.Height), 0, 0, copyImage.Width, copyImage.Height, GraphicsUnit.Pixel); g.Dispose(); image.Save(ImageFilePath); image.Dispose(); } } //获取图片的高度和宽度 System.Drawing.Image Img = System.Drawing.Image.FromStream(newFile); _Width = Img.Width; _Height = Img.Height; //生成缩略图部分 if (_IsCreateImg) { #region 缩略图大小只设置了最大范围,并不是实际大小 float realbili = (float)_Width / (float)_Height; float wishbili = (float)_sWidth / (float)_sHeight; //实际图比缩略图最大尺寸更宽矮,以宽为准 if (realbili > wishbili) { _sHeight = (int)((float)_sWidth / realbili); } //实际图比缩略图最大尺寸更高长,以高为准 else { _sWidth = (int)((float)_sHeight * realbili); } #endregion this.OutThumbFileName = FName.Split('.').GetValue(0).ToString() + "_s." + FName.Split('.').GetValue(1).ToString(); string ImgFilePath = _SavePath + this.OutThumbFileName; System.Drawing.Image newImg = Img.GetThumbnailImage(_sWidth, _sHeight, null, System.IntPtr.Zero); newImg.Save(ImgFilePath); newImg.Dispose(); _Iss = true; } if (_IsDraw) { if (File.Exists(_SavePath + FName.Split('.').GetValue(0).ToString() + "_temp." + FName.Split('.').GetValue(1).ToString())) { newFile.Dispose(); File.Delete(_SavePath + FName.Split('.').GetValue(0).ToString() + "_temp." + FName.Split('.').GetValue(1).ToString()); } } newFile.Close(); newFile.Dispose(); _OutFileName = FName; _FileSize = _FileSizeTemp; _Error = 0; return; } catch (Exception ex) { _Error = 4; return; } }
public DataRow AddImage(int AlbumId, string Caption, HttpPostedFile Image, int Sort = 100000) { if (Image == null || Image.ContentLength <= 0) { return(null); } if (!Directory.Exists(WebContext.Server.MapPath("~/temp"))) { Directory.CreateDirectory(WebContext.Server.MapPath("~/temp")); } string path = WebContext.Server.MapPath("~/temp"); path = Path.Combine(path, Image.FileName); Image.SaveAs(path); DataRow row = AddImage(AlbumId, Caption, path, Sort); File.Delete(path); return(row); /* * * AlbumsDS _ds = new AlbumsDS(); * * IDataAdapter Adp = base.GetAdapter(cte.PhotoAlbumImagesAdp); * AlbumsDS.PhotoAlbumImagesRow row = _ds.PhotoAlbumImages.NewPhotoAlbumImagesRow(); * * row.AlbumId = AlbumId; * row.Caption = Caption; * row.Sort = 100; * row.DateAdded = DateTime.Now; * row.DateModified = DateTime.Now; * * _ds.PhotoAlbumImages.AddPhotoAlbumImagesRow(row); * base.UpdateData(Adp, _ds); * * string path = WebContext.Server.MapPath("~/" + lw.CTE.Folders.PhotoAlbums); * path = System.IO.Path.Combine(path, string.Format("Album{0}", AlbumId)); * string largePath = Path.Combine(path, "Large"); * string thumbPath = Path.Combine(path, "Thumb"); * * if (!Directory.Exists(thumbPath)) * Directory.CreateDirectory(thumbPath); * * if (!Directory.Exists(largePath)) * Directory.CreateDirectory(largePath); * * Config cfg = new Config(); * * string ext = StringUtils.GetFileExtension(Image.FileName); * string fileName = StringUtils.GetFriendlyFileName(Image.FileName); * * string _ImageName = string.Format("{0}_{1}.{2}", fileName, row.Id, ext); * * string ImageName = string.Format("{0}\\{1}", largePath, _ImageName); * string thumbImageName = string.Format("{0}\\{1}", thumbPath, _ImageName); * * Image.SaveAs(ImageName); * try * { * if (cfg.GetKey("AlbumsResizeLarge") == "on") * { * int _Width = Int32.Parse(cfg.GetKey("AlbumsLargeWidth")); * int _Height = Int32.Parse(cfg.GetKey("AlbumsLargeHeight")); * * lw.GraphicUtils.ImageUtils.Resize(ImageName, ImageName, _Width, _Height); * } * if (cfg.GetKey("AlbumResizeThumbs") == "on") * { * int Width = Int32.Parse(cfg.GetKey("AlbumsThumbWidth")); * int Height = Int32.Parse(cfg.GetKey("AlbumsThumbHeight")); * * //TODO: add a parameter to choose between the below * //lw.GraphicUtils.ImageUtils.Resize(ImageName, thumbImageName, Width, Height); * //lw.GraphicUtils.ImageUtils.CreateThumb(ImageName, thumbImageName, Width, Height); * lw.GraphicUtils.ImageUtils.CropImage(ImageName, thumbImageName, Width, Height, ImageUtils.AnchorPosition.Default); * } * else * File.Copy(ImageName, thumbImageName); * } * catch (Exception ex) * { * ErrorContext.Add("resize-image", "Unable to resize album image.<br><span class=hid>" + ex.Message + "</span>"); * } * * row.FileName = _ImageName; * base.UpdateData(Adp, _ds); * * UpdateAlbumModified(AlbumId, DateTime.Now); * * return row; * */ }
public void ProcessRequest(HttpContext context) { if (context.Request.Files.Count > 0) { var billPeriodFromContext = context.Request.QueryString["billperiod"].ToString(); var zoneTypeFromContext = context.Request.QueryString["zonetype"].ToString(); int billPeriod = int.Parse(billPeriodFromContext); BCS_Context db = new BCS_Context(); HttpFileCollection files = context.Request.Files; HttpPostedFile file = files["uploadData"]; if ((file != null) && (file.ContentLength > 0) && !string.IsNullOrEmpty(file.FileName)) { using (var transaction = db.Database.BeginTransaction()) { var excelHelper = new Helper.ExcelHelper(); List <AdminFee> adminfees = new List <AdminFee>(); db.AdminFee.RemoveRange(db.AdminFee.Where(m => m.BillingPeriodId == billPeriod && m.Upload_Type.ToUpper().Trim() == zoneTypeFromContext.ToUpper().Trim()).ToList()); db.SaveChanges(); try { var uname = HttpContext.Current.User.Identity.Name; ApplicationDbContext dbcontext = new ApplicationDbContext(); var user = dbcontext.Users.Where(m => m.UserName == uname).FirstOrDefault(); var zone = user.ZoneGroup; var zoneid = db.ZoneGroup.Where(m => m.ZoneGroupCode == zone).FirstOrDefault().ZoneGroupId; var prop = excelHelper.GetProperties(typeof(AdminFee), new[] { "Ecozone", "Zone_Type", "Company_Name", "Enterprise_Type", "Employment", "Zone_Code", "Month", "Year", "Comp_Code", "Developer", "Dev_Comp_Code", "Total_Locators", "Total_Employment", "BillingPeriodId", "Upload_Type" }); var data = excelHelper.ReadData <AdminFee>(file.InputStream, file.FileName, prop, billPeriod, "Admin", zoneTypeFromContext); foreach (var item in data) { var groupId = ""; try { string tempZone = ""; if (zoneTypeFromContext.ToUpper().Trim() != "ALL") { if (item.Zone_Type.ToUpper().Trim() == "IT CENTER" || item.Zone_Type.ToUpper().Trim() == "IT PARK") { tempZone = "IT"; } else if (item.Zone_Type.ToUpper().Trim() != "IT CENTER" && item.Zone_Type.ToUpper().Trim() != "IT PARK" && item.Zone_Type.ToUpper().Trim() != "MANUFACTURING CEZ") { tempZone = "OTHERS"; } else if (item.Zone_Type.ToUpper().Trim() == "MANUFACTURING SEZ") { tempZone = "MANUFACTURING"; } else { tempZone = item.Zone_Type.ToUpper().Trim(); } //tempZone = item.Zone_Type.ToUpper().Trim() == "IT CENTER" || item.Zone_Type.ToUpper().Trim() == "IT PARK" ? // "IT" : item.Zone_Type.ToUpper().Trim(); //tempZone = item.Zone_Type.ToUpper().Trim() != "IT CENTER" && item.Zone_Type.ToUpper().Trim() != "IT PARK" && item.Zone_Type.ToUpper().Trim() != "MANUFACTURING CEZ" ? // "OTHERS" : item.Zone_Type.ToUpper().Trim(); //tempZone = item.Zone_Type.ToUpper().Trim() == "MANUFACTURING CEZ" ? // "MANUFACTURING" : item.Zone_Type.ToUpper().Trim(); } if (tempZone == zoneTypeFromContext.ToUpper().Trim()) { try { var zoneCode = db.Company.Where(m => m.CompanyCode == item.Dev_Comp_Code).FirstOrDefault().ZoneCode ?? ""; if (zoneCode != null || zoneCode != "") { groupId = db.Zone.Where(m => m.ZoneCode == zoneCode).FirstOrDefault().ZoneGroup ?? ""; } } catch (Exception) { IOHelper.LogTxt(item.Dev_Comp_Code, billPeriodFromContext, zoneTypeFromContext); //throw new Exception("Zone code is has no match in current record " + item.Dev_Comp_Code); } } else { throw new Exception("Missmatch zone type " + tempZone); } } catch (Exception ex) { throw new Exception(ex.Message); } if (groupId == zoneid.ToString()) { adminfees.Add(item); } } db.AdminFee.AddRange(adminfees); db.SaveChanges(); transaction.Commit(); } catch (Exception ex) { transaction.Rollback(); HttpContext.Current.Response.ContentType = "text/plain"; HttpContext.Current.Response.Write(ex.Message); throw new Exception(ex.Message); } } } //if ((file != null) && (file.ContentLength > 0) && !string.IsNullOrEmpty(file.FileName)) // { // string filename = file.FileName; // string filecontenttype = file.ContentType; // byte[] filebytes = new byte[file.ContentLength]; // var data = file.InputStream.Read(filebytes, 0, Convert.ToInt32(file.ContentLength)); // //int billingPeriodId = Convert.ToInt32(frm["BillingPeriod"].ToString()); // List<AdminFee> adminFee = new List<AdminFee>(); // using (var transaction = db.Database.BeginTransaction()) // { // db.AdminFee.RemoveRange(db.AdminFee.Where(m => m.BillingPeriodId == billPeriod).ToList()); // db.SaveChanges(); // try // { // using (var package = new ExcelPackage(file.InputStream)) // { // List<String> notRegisteredCompany = new List<string>(); // var currentSheet = package.Workbook.Worksheets; // var workSheet = currentSheet.First(); // var noOfCol = workSheet.Dimension.End.Column; // var noOfRow = workSheet.Dimension.End.Row; // for (int rowIterator = 2; rowIterator <= noOfRow; rowIterator++) // { // AdminFee adminfee = new AdminFee(); // adminfee.Ecozone = workSheet.Cells[rowIterator, 1].Value != null ? workSheet.Cells[rowIterator, 1].Value.ToString() : ""; // adminfee.Zone_Type = workSheet.Cells[rowIterator, 2].Value != null ? workSheet.Cells[rowIterator, 2].Value.ToString() : ""; // adminfee.Company_Name = workSheet.Cells[rowIterator, 3].Value != null ? workSheet.Cells[rowIterator, 3].Value.ToString() : ""; // adminfee.Enterprise_Type = workSheet.Cells[rowIterator, 4].Value != null ? workSheet.Cells[rowIterator, 4].Value.ToString() : ""; // adminfee.Employment = workSheet.Cells[rowIterator, 5].Value != null ? workSheet.Cells[rowIterator, 5].Value.ToString() : ""; // adminfee.Zone_Code = workSheet.Cells[rowIterator, 6].Value != null ? workSheet.Cells[rowIterator, 6].Value.ToString() : ""; // adminfee.Month = workSheet.Cells[rowIterator, 7].Value != null ? workSheet.Cells[rowIterator, 7].Value.ToString() : ""; // adminfee.Year = workSheet.Cells[rowIterator, 8].Value != null ? workSheet.Cells[rowIterator, 8].Value.ToString() : ""; // adminfee.Comp_Code = workSheet.Cells[rowIterator, 9].Value != null ? workSheet.Cells[rowIterator, 9].Value.ToString() : ""; // adminfee.Developer = workSheet.Cells[rowIterator, 10].Value != null ? workSheet.Cells[rowIterator, 10].Value.ToString() : ""; // adminfee.Dev_Comp_Code = workSheet.Cells[rowIterator, 11].Value != null ? workSheet.Cells[rowIterator, 11].Value.ToString() : ""; // adminfee.Total_Locators = workSheet.Cells[rowIterator, 12].Value != null ? workSheet.Cells[rowIterator, 12].Value.ToString() : ""; // adminfee.Total_Employment = workSheet.Cells[rowIterator, 13].Value != null ? workSheet.Cells[rowIterator, 13].Value.ToString() : ""; // adminfee.BillingPeriodId = billPeriod; // if (!db.Company.Any(m => m.CompanyCode == adminfee.Comp_Code)) // notRegisteredCompany.Add(adminfee.Company_Name); // db.AdminFee.Add(adminfee); // db.SaveChanges(); // } // //TempData["notRegisteredCompany"] = notRegisteredCompany; // //TempData["TransactionSuccess"] = "Complete"; // transaction.Commit(); // } // } // catch (Exception) // { // transaction.Rollback(); // //TempData["TransactionSuccess"] = "Failed"; // } // } // } } }
public bool UpdateAlbum(int AlbumId, string Name, string DisplayName, string Description, bool status, int Sort, bool HasIntroPage, int CategoryId, bool DeleteImage, HttpPostedFile Image, Languages lan, DateTime?AlbumDate) { AlbumsDS _ds = new AlbumsDS(); AlbumsDSTableAdapters.PhotoAlbumsTableAdapter adp = new AlbumsDSTableAdapters.PhotoAlbumsTableAdapter(); DataRow album = this.GetPhotoAlbums(string.Format("Id={0}", AlbumId))[0].Row; album["Name"] = StringUtils.ToURL(DisplayName); album["DisplayName"] = DisplayName; album["Description"] = Description; album["Status"] = status; album["Sort"] = Sort; album["HasIntroPage"] = HasIntroPage; album["CategoryId"] = CategoryId; album["DateAdded"] = (DateTime)album["DateAdded"]; album["DateModified"] = DateTime.Now; album["Image"] = album["Image"].ToString(); album["Language"] = (short)lan; if (AlbumDate != null) { album["AlbumDate"] = AlbumDate.Value; } adp.Update(album); string path = WebContext.Server.MapPath("~/" + lw.CTE.Folders.PhotoAlbums); path = System.IO.Path.Combine(path, string.Format("Album{0}", album["Id"])); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); Directory.CreateDirectory(Path.Combine(path, "Original")); Directory.CreateDirectory(Path.Combine(path, "Large")); Directory.CreateDirectory(Path.Combine(path, "Thumb")); } bool del = (DeleteImage || (Image != null && Image.ContentLength > 0)) && album["Image"].ToString() != ""; bool updateData = false; if (DeleteImage) { string fileName = Path.Combine(path, album["Image"].ToString()); if (File.Exists(fileName)) { File.Delete(fileName); } fileName = Path.Combine(path, "Large_" + album["Image"].ToString()); if (File.Exists(fileName)) { File.Delete(fileName); } fileName = Path.Combine(path, "Thumb_" + album["Image"].ToString()); if (File.Exists(fileName)) { File.Delete(fileName); } album["Image"] = ""; updateData = true; } //if (!DeleteImage && Image != null && Image.ContentLength > 0) if (Image != null && Image.ContentLength > 0) { Config cfg = new Config(); string fileName = StringUtils.GetFileName(Image.FileName); string ImageName = string.Format("{0}\\{1}", path, fileName); string largeImageName = string.Format("{0}\\Large_{1}", path, fileName); string thumbImageName = string.Format("{0}\\Thumb_{1}", path, fileName); Image.SaveAs(ImageName); if (cfg.GetKey("AlbumImage") == "on") { try { Dimension largeImageSize = new Dimension(cte.CoverPhotoDefaultSize); Dimension thumbImageSize = new Dimension(cte.CoverPhotoDefaultThumbSize); if (!string.IsNullOrWhiteSpace(cfg.GetKey(cte.CoverPhotoSize))) { largeImageSize = new Dimension(cfg.GetKey(cte.CoverPhotoSize)); } if (!string.IsNullOrWhiteSpace(cfg.GetKey(cte.CoverPhotoThumbSize))) { thumbImageSize = new Dimension(cfg.GetKey(cte.CoverPhotoThumbSize)); } lw.GraphicUtils.ImageUtils.Resize(ImageName, largeImageName, largeImageSize.IntWidth, largeImageSize.IntHeight); lw.GraphicUtils.ImageUtils.CropImage(ImageName, thumbImageName, thumbImageSize.IntWidth, thumbImageSize.IntHeight, ImageUtils.AnchorPosition.Default); } catch (Exception ex) { ErrorContext.Add("resize-image", "Unable to resize album image.<br><span class=hid>" + ex.Message + "</span>"); } } album["Image"] = fileName; updateData = true; } if (updateData) { adp.Update(album); } return(true); }
public Dictionary <string, object> UploadExcel(string UserId, string EntityId) { //string message = ""; string FileName1 = ""; HttpResponseMessage result = null; var httpRequest = HttpContext.Current.Request; DataSet excelRecords = new DataSet(); if (httpRequest.Files.Count > 0) { HttpPostedFile file = httpRequest.Files[0]; Stream stream = file.InputStream; //IExcelDataReader reader = null; // string eid1 = DbSecurity.Decrypt(HttpContext.Current.Server.UrlDecode(EntityId.Replace("_", "%"))); string FileName = Path.GetFileName(file.FileName); FileName1 = Path.GetFileName(file.FileName); string Extension = Path.GetExtension(file.FileName); Regex illegalInFileName = new Regex(@"[\\/:*?""<>|]"); string FolderPath = HttpContext.Current.Server.MapPath("/ExportedFiles"); string FilePath = FolderPath + '/' + FileName; if (!Directory.Exists(FolderPath)) // CHECK IF THE FOLDER EXISTS. IF NOT, CREATE A NEW FOLDER. { Directory.CreateDirectory(FolderPath); } if (File.Exists(FilePath)) { File.Delete(FilePath); } file.SaveAs(FilePath); if (Extension == ".xls") { FilePath = FilePath.Replace(".xls", ".xlsx"); if (File.Exists(FilePath)) { File.Delete(FilePath); } FilePath = FilePath.Replace(".xlsx", ".xls"); FileInfo f = new FileInfo(FilePath); f.MoveTo(Path.ChangeExtension(FilePath, ".xlsx")); Extension = ".xlsx"; FilePath = FilePath.Replace(".xls", ".xlsx"); } string conStr = ""; if (Extension == ".xls" || Extension == ".xlsx") { switch (Extension) { case ".xls": //Excel 97-03 conStr = System.Configuration.ConfigurationManager.ConnectionStrings["Excel03ConString"] .ConnectionString; break; case ".xlsx": //Excel 07 conStr = System.Configuration.ConfigurationManager.ConnectionStrings["Excel07ConString"] .ConnectionString; break; } conStr = String.Format(conStr, FilePath, true); OleDbConnection connExcel = new OleDbConnection(conStr); OleDbCommand cmdExcel = new OleDbCommand(); OleDbDataAdapter oda = new OleDbDataAdapter(); cmdExcel.Connection = connExcel; //Get the name of First Sheet connExcel.Open(); System.Data.DataTable dtExcelSchema; dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null); string SheetName = dtExcelSchema.Rows[0]["Table_Name"].ToString(); connExcel.Close(); connExcel.Open(); cmdExcel.CommandText = "SELECT * From [" + SheetName + "]"; oda.SelectCommand = cmdExcel; oda.Fill(dt); if (dt.Rows.Count == 0) { } if (dt.Rows.Count > int.Parse(System.Configuration.ConfigurationManager.AppSettings["LegacyCount"])) { } connExcel.Close(); } //excelRecords = reader.AsDataSet(); // reader.Close(); } else { result = Request.CreateResponse(HttpStatusCode.BadRequest); } return(umrn.UploadExcel(GetXmlByDatable(dt), UserId, EntityId, FileName1)); }
public int AddAlbum(string Name, string DisplayName, string Description, bool status, int Sort, bool HasIntroPage, int CategoryId, HttpPostedFile Image, Languages lan, DateTime?AlbumDate, bool FixedSize) { AlbumsDS _ds = new AlbumsDS(); IDataAdapter Adp = base.GetAdapter(cte.PhotoAlbumsAdp); AlbumsDS.PhotoAlbumsRow row = _ds.PhotoAlbums.NewPhotoAlbumsRow(); row.Name = StringUtils.ToURL(DisplayName); row.DisplayName = DisplayName; row.Description = Description; row.Status = status; row.Sort = Sort; row.HasIntroPage = HasIntroPage; row.CategoryId = CategoryId; row.DateAdded = DateTime.Now; row.DateModified = DateTime.Now; row.Language = (short)lan; if (AlbumDate != null) { row.AlbumDate = AlbumDate.Value; } _ds.PhotoAlbums.AddPhotoAlbumsRow(row); base.UpdateData(Adp, _ds); string path = WebContext.Server.MapPath("~/" + lw.CTE.Folders.PhotoAlbums); path = System.IO.Path.Combine(path, string.Format("Album{0}", row.Id)); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } Directory.CreateDirectory(Path.Combine(path, "Large")); Directory.CreateDirectory(Path.Combine(path, "Thumb")); Directory.CreateDirectory(Path.Combine(path, "Original")); if (Image != null && Image.ContentLength > 0) { Config cfg = new Config(); string fileName = StringUtils.GetFileName(Image.FileName); string ImageName = string.Format("{0}\\{1}", path, fileName); string largeImageName = string.Format("{0}\\Large_{1}", path, fileName); string thumbImageName = string.Format("{0}\\Thumb_{1}", path, fileName); Image.SaveAs(ImageName); try { Dimension largeImageSize = new Dimension(cte.CoverPhotoDefaultSize); Dimension thumbImageSize = new Dimension(cte.CoverPhotoDefaultThumbSize); if (!string.IsNullOrWhiteSpace(cfg.GetKey(cte.CoverPhotoSize))) { largeImageSize = new Dimension(cfg.GetKey(cte.CoverPhotoSize)); } if (!string.IsNullOrWhiteSpace(cfg.GetKey(cte.CoverPhotoThumbSize))) { thumbImageSize = new Dimension(cfg.GetKey(cte.CoverPhotoThumbSize)); } ////ImageUtils.Resize(ImageName, ImageName, _Width, _Height); //if (FixedSize) // lw.GraphicUtils.ImageUtils.CreateThumb(ImageName, largeImageName, largeImageSize.IntWidth, largeImageSize.IntHeight, FixedSize); //else // lw.GraphicUtils.ImageUtils.CreateThumb(ImageName, largeImageName, largeImageSize.IntWidth, largeImageSize.IntHeight); ////TODO: add a parameter to choose between the below ////lw.GraphicUtils.ImageUtils.Resize(ImageName, thumbImageName, Width, Height); //lw.GraphicUtils.ImageUtils.CreateThumb(ImageName, thumbImageName, thumbImageSize.IntWidth, thumbImageSize.IntHeight, FixedSize); lw.GraphicUtils.ImageUtils.Resize(ImageName, largeImageName, largeImageSize.IntWidth, largeImageSize.IntHeight); lw.GraphicUtils.ImageUtils.CropImage(ImageName, thumbImageName, thumbImageSize.IntWidth, thumbImageSize.IntHeight, ImageUtils.AnchorPosition.Default); } catch (Exception ex) { ErrorContext.Add("resize-image", "Unable to resize album image.<br><span class=hid>" + ex.Message + "</span>"); } row.Image = fileName; base.UpdateData(Adp, _ds); } return(row.Id); }
protected void btn_Import_Click_Click(object sender, EventArgs e) { List <string> listc = new List <string>(); List <string> listm = 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 sheet = wk.GetSheetAt(0); //循环读取每一行数据,由于execel有列名以及序号,从1开始 string sqlc = ""; string sqlm = ""; string ncs = "本期数"; string qms = "本年累计数"; IRow row1 = sheet.GetRow(44); ICell cell0 = row1.GetCell(0); string rqbhc = cell0.StringCellValue.ToString().Trim(); string rqbhm = cell0.StringCellValue.ToString().Trim();//得到修改人员编码 string sqlTextchk = "select * from TBFM_LRFP where RQBH='" + cell0.StringCellValue.ToString().Trim() + "'"; System.Data.DataTable dtchk = DBCallCommon.GetDTUsingSqlText(sqlTextchk); if (dtchk.Rows.Count > 0) { Response.Write("<script>alert('日期编号已存在!');</script>"); return; } sqlc = "'" + rqbhc + "','" + ncs + "'"; sqlm = "'" + rqbhm + "','" + qms + "'"; IRow row4 = sheet.GetRow(47); ICell cell24 = row4.GetCell(2); ICell cell34 = row4.GetCell(3); sqlc += ",'" + cell24.NumericCellValue.ToString("0.00").Trim() + "'"; sqlm += ",'" + cell34.NumericCellValue.ToString("0.00").Trim() + "'"; IRow row5 = sheet.GetRow(48); ICell cell25 = row5.GetCell(2); ICell cell35 = row5.GetCell(3); sqlc += ",'" + cell25.NumericCellValue.ToString("0.00").Trim() + "'"; sqlm += ",'" + cell35.NumericCellValue.ToString("0.00").Trim() + "'"; IRow row6 = sheet.GetRow(49); ICell cell26 = row6.GetCell(2); ICell cell36 = row6.GetCell(3); sqlc += ",'" + cell26.NumericCellValue.ToString("0.00").Trim() + "'"; sqlm += ",'" + cell36.NumericCellValue.ToString("0.00").Trim() + "'"; IRow row7 = sheet.GetRow(50); ICell cell27 = row7.GetCell(2); ICell cell37 = row7.GetCell(3); sqlc += ",'" + cell27.NumericCellValue.ToString("0.00").Trim() + "'"; sqlm += ",'" + cell37.NumericCellValue.ToString("0.00").Trim() + "'"; IRow row8 = sheet.GetRow(51); ICell cell28 = row8.GetCell(2); ICell cell38 = row8.GetCell(3); sqlc += ",'" + cell28.NumericCellValue.ToString("0.00").Trim() + "'"; sqlm += ",'" + cell38.NumericCellValue.ToString("0.00").Trim() + "'"; IRow row9 = sheet.GetRow(52); ICell cell29 = row9.GetCell(2); ICell cell39 = row9.GetCell(3); sqlc += ",'" + cell29.NumericCellValue.ToString("0.00").Trim() + "'"; sqlm += ",'" + cell39.NumericCellValue.ToString("0.00").Trim() + "'"; IRow row10 = sheet.GetRow(53); ICell cell210 = row10.GetCell(2); ICell cell310 = row10.GetCell(3); sqlc += ",'" + cell210.NumericCellValue.ToString("0.00").Trim() + "'"; sqlm += ",'" + cell310.NumericCellValue.ToString("0.00").Trim() + "'"; IRow row11 = sheet.GetRow(54); ICell cell211 = row11.GetCell(2); ICell cell311 = row11.GetCell(3); sqlc += ",'" + cell211.NumericCellValue.ToString("0.00").Trim() + "'"; sqlm += ",'" + cell311.NumericCellValue.ToString("0.00").Trim() + "'"; IRow row12 = sheet.GetRow(55); ICell cell212 = row12.GetCell(2); ICell cell312 = row12.GetCell(3); sqlc += ",'" + cell212.NumericCellValue.ToString("0.00").Trim() + "'"; sqlm += ",'" + cell312.NumericCellValue.ToString("0.00").Trim() + "'"; IRow row13 = sheet.GetRow(56); ICell cell213 = row13.GetCell(2); ICell cell313 = row13.GetCell(3); sqlc += ",'" + cell213.NumericCellValue.ToString("0.00").Trim() + "'"; sqlm += ",'" + cell313.NumericCellValue.ToString("0.00").Trim() + "'"; IRow row14 = sheet.GetRow(57); ICell cell214 = row14.GetCell(2); ICell cell314 = row14.GetCell(3); sqlc += ",'" + cell214.NumericCellValue.ToString("0.00").Trim() + "'"; sqlm += ",'" + cell314.NumericCellValue.ToString("0.00").Trim() + "'"; IRow row15 = sheet.GetRow(58); ICell cell215 = row15.GetCell(2); ICell cell315 = row15.GetCell(3); sqlc += ",'" + cell215.NumericCellValue.ToString("0.00").Trim() + "'"; sqlm += ",'" + cell315.NumericCellValue.ToString("0.00").Trim() + "'"; IRow row16 = sheet.GetRow(58); ICell cell216 = row16.GetCell(2); ICell cell316 = row16.GetCell(3); sqlc += ",'" + cell216.NumericCellValue.ToString("0.00").Trim() + "'"; sqlm += ",'" + cell316.NumericCellValue.ToString("0.00").Trim() + "'"; IRow row17 = sheet.GetRow(60); ICell cell217 = row17.GetCell(2); ICell cell317 = row17.GetCell(3); sqlc += ",'" + cell217.NumericCellValue.ToString("0.00").Trim() + "'"; sqlm += ",'" + cell317.NumericCellValue.ToString("0.00").Trim() + "'"; IRow row18 = sheet.GetRow(61); ICell cell218 = row18.GetCell(2); ICell cell318 = row18.GetCell(3); sqlc += ",'" + cell218.NumericCellValue.ToString("0.00").Trim() + "'"; sqlm += ",'" + cell318.NumericCellValue.ToString("0.00").Trim() + "'"; IRow row19 = sheet.GetRow(62); ICell cell219 = row19.GetCell(2); ICell cell319 = row19.GetCell(3); sqlc += ",'" + cell219.NumericCellValue.ToString("0.00").Trim() + "'"; sqlm += ",'" + cell319.NumericCellValue.ToString("0.00").Trim() + "'"; IRow row20 = sheet.GetRow(63); ICell cell220 = row20.GetCell(2); ICell cell320 = row20.GetCell(3); sqlc += ",'" + cell220.NumericCellValue.ToString("0.00").Trim() + "'"; sqlm += ",'" + cell320.NumericCellValue.ToString("0.00").Trim() + "'"; IRow row21 = sheet.GetRow(64); ICell cell221 = row21.GetCell(2); ICell cell321 = row21.GetCell(3); sqlc += ",'" + cell221.NumericCellValue.ToString("0.00").Trim() + "'"; sqlm += ",'" + cell321.NumericCellValue.ToString("0.00").Trim() + "'"; IRow row22 = sheet.GetRow(65); ICell cell222 = row22.GetCell(2); ICell cell322 = row22.GetCell(3); sqlc += ",'" + cell222.NumericCellValue.ToString("0.00").Trim() + "'"; sqlm += ",'" + cell322.NumericCellValue.ToString("0.00").Trim() + "'"; IRow row23 = sheet.GetRow(66); ICell cell223 = row23.GetCell(2); ICell cell323 = row23.GetCell(3); sqlc += ",'" + cell223.NumericCellValue.ToString("0.00").Trim() + "'"; sqlm += ",'" + cell323.NumericCellValue.ToString("0.00").Trim() + "'"; IRow row24 = sheet.GetRow(67); ICell cell224 = row24.GetCell(2); ICell cell324 = row24.GetCell(3); sqlc += ",'" + cell224.NumericCellValue.ToString("0.00").Trim() + "'"; sqlm += ",'" + cell324.NumericCellValue.ToString("0.00").Trim() + "'"; IRow row27 = sheet.GetRow(70); ICell cell327 = row27.GetCell(3); sqlm += ",'" + cell327.NumericCellValue.ToString("0.00").Trim() + "'"; IRow row28 = sheet.GetRow(71); ICell cell328 = row28.GetCell(3); sqlm += ",'" + cell328.NumericCellValue.ToString("0.00").Trim() + "'"; IRow row29 = sheet.GetRow(72); ICell cell329 = row29.GetCell(3); sqlm += ",'" + cell329.NumericCellValue.ToString("0.00").Trim() + "'"; IRow row30 = sheet.GetRow(73); ICell cell230 = row30.GetCell(2); ICell cell330 = row30.GetCell(3); sqlm += ",'" + cell330.NumericCellValue.ToString("0.00").Trim() + "'"; IRow row31 = sheet.GetRow(74); ICell cell331 = row31.GetCell(3); sqlm += ",'" + cell331.NumericCellValue.ToString("0.00").Trim() + "'"; IRow row32 = sheet.GetRow(75); ICell cell332 = row32.GetCell(3); sqlm += ",'" + cell332.NumericCellValue.ToString("0.00").Trim() + "'"; IRow row33 = sheet.GetRow(76); ICell cell333 = row33.GetCell(3); sqlm += ",'" + cell333.NumericCellValue.ToString("0.00").Trim() + "'"; IRow row34 = sheet.GetRow(77); ICell cell334 = row34.GetCell(3); sqlm += ",'" + cell334.NumericCellValue.ToString("0.00").Trim() + "'"; IRow row35 = sheet.GetRow(78); ICell cell235 = row35.GetCell(2); ICell cell335 = row35.GetCell(3); sqlm += ",'" + cell335.NumericCellValue.ToString("0.00").Trim() + "'"; IRow row36 = sheet.GetRow(79); ICell cell336 = row36.GetCell(3); sqlm += ",'" + cell336.NumericCellValue.ToString("0.00").Trim() + "'"; IRow row37 = sheet.GetRow(80); ICell cell237 = row37.GetCell(2); ICell cell337 = row37.GetCell(3); sqlm += ",'" + cell337.NumericCellValue.ToString("0.00").Trim() + "'"; IRow row38 = sheet.GetRow(81); ICell cell338 = row38.GetCell(3); sqlm += ",'" + cell338.NumericCellValue.ToString("0.00").Trim() + "'"; IRow row39 = sheet.GetRow(82); ICell cell239 = row39.GetCell(2); ICell cell339 = row39.GetCell(3); sqlm += ",'" + cell339.NumericCellValue.ToString("0.00").Trim() + "'"; IRow row40 = sheet.GetRow(83); ICell cell340 = row40.GetCell(3); sqlm += ",'" + cell340.NumericCellValue.ToString("0.00").Trim() + "'"; IRow row41 = sheet.GetRow(84); ICell cell341 = row41.GetCell(3); sqlm += ",'" + cell341.NumericCellValue.ToString("0.00").Trim() + "'"; #region 存入数据库 string sqlTxtc = string.Format("insert into TBFM_LRFP({0}) values({1})", "RQBH,LRFP_TYPE,LRFP_YYSR,LRFP_YYSR_ZYSR,LRFP_YYSR_QTSR,LRFP_YYSR_JYCB,LRFP_YYSR_ZYCB,LRFP_YYSR_QTCB,LRFP_YYSR_SJFJ,LRFP_YYSR_XSFY,LRFP_YYSR_GLFY,LRFP_YYSR_CWFY,LRFP_YYSR_JZSS,LRFP_YYSR_JZBD,LRFP_YYSR_TZSY,LRFP_YYSR_LYHY,LRFP_YYLR,LRFP_YYLR_YWSR,LRFP_YYLR_YWZC,LRFP_YYLR_FLDSS,LRFP_LRZE,LRFP_LRZE_SDSF,LRFP_JLR", sqlc); string sqlTxtm = string.Format("insert into TBFM_LRFP({0}) values({1})", "RQBH,LRFP_TYPE,LRFP_YYSR,LRFP_YYSR_ZYSR,LRFP_YYSR_QTSR,LRFP_YYSR_JYCB,LRFP_YYSR_ZYCB,LRFP_YYSR_QTCB,LRFP_YYSR_SJFJ,LRFP_YYSR_XSFY,LRFP_YYSR_GLFY,LRFP_YYSR_CWFY,LRFP_YYSR_JZSS,LRFP_YYSR_JZBD,LRFP_YYSR_TZSY,LRFP_YYSR_LYHY,LRFP_YYLR,LRFP_YYLR_YWSR,LRFP_YYLR_YWZC,LRFP_YYLR_FLDSS,LRFP_LRZE,LRFP_LRZE_SDSF,LRFP_JLR,LRFP_NCWFP,LRFP_QTZR,LRFP_KGFP,LRFP_KGFP_FDYYGJ,LRFP_KGFP_FDGY,LRFP_KGFP_JLFL,LRFP_KGFP_CBJJ,LRFP_KGFP_QYFZ,LRFP_KGFP_LRGH,LRFP_KGTZFP,LRFP_KGTZFP_YFYXG,LRFP_KGTZFP_RYYY,LRFP_KGTZFP_YFPTG,LRFP_KGTZFP_ZZZB,LRFP_WFPLR", sqlm); listc.Add(sqlTxtc); listm.Add(sqlTxtm); #endregion } DBCallCommon.ExecuteTrans(listc); DBCallCommon.ExecuteTrans(listm); 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()); }
public void ProcessRequest(HttpContext context) { //最大文件大小 int maxSize = 10 * 1024 * 1024; this.context = context; HttpPostedFile uploadFile = context.Request.Files["imgFile"]; if (uploadFile == null) { showError("请选择文件。"); } String fileName = uploadFile.FileName; String fileExt = Path.GetExtension(fileName).ToLower(); if (uploadFile.InputStream == null || uploadFile.InputStream.Length > maxSize) { showError("上传文件大小不能超过10M。"); } if (String.IsNullOrEmpty(fileExt) || !"gif,jpg,jpeg,png,bmp".Split(',').Contains(fileExt.Substring(1))) { showError("上传文件扩展名是不允许的扩展名。\n只允许gif,jpg,jpeg,png,bmp格式。"); } string visualpath = SysConfig.FileVisualPath; string localpath = context.Server.MapPath(visualpath); var imgid = Guid.NewGuid(); var subdir = DateTime.Now.ToString("yyyyMMdd"); DirectoryInfo localbigdi = new DirectoryInfo(string.Format("{0}Pic\\{1}\\", localpath, subdir)); if (!localbigdi.Exists) { localbigdi.Create(); } string fullName = string.Format("{0}Pic\\{1}\\{2}{3}", localpath, subdir, imgid, fileExt); string fullwebpath = string.Format("{0}Pic/{1}/{2}{3}", visualpath, subdir, imgid, fileExt); try { if (uploadFile.ContentLength > 0) { uploadFile.SaveAs(fullName); //转为jpg格式的文件 if (Path.GetExtension(fullName).ToLower() != ".jpg") { imgid = Guid.NewGuid(); Bitmap bit = new Bitmap(fullName); string oldname = fullName; fullName = string.Format("{0}Pic\\{1}\\{2}.jpg", localpath, subdir, imgid); fullwebpath = string.Format("{0}Pic/{1}/{2}.jpg", visualpath, subdir, imgid); bit.Save(fullName, ImageFormat.Jpeg); bit.Dispose(); File.Delete(oldname); } } Hashtable hash = new Hashtable(); hash["error"] = 0; hash["url"] = fullwebpath; hash["width"] = "100%"; context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8"); context.Response.Write(PluSoft.Utils.JSON.Encode(hash)); } catch (Exception ex) { showError(ex.Message); } finally { context.Response.End(); } }
/// <summary> /// Enables processing of HTTP Web requests by a custom HttpHandler that implements the <see cref="T:System.Web.IHttpHandler" /> interface. /// </summary> /// <param name="context">An <see cref="T:System.Web.HttpContext" /> object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests.</param> /// <exception cref="WebFaultException">Must be logged in</exception> public virtual void ProcessRequest(HttpContext context) { if (!context.User.Identity.IsAuthenticated) { // If not, see if there's a valid token string authToken = context.Request.Headers["Authorization-Token"]; if (string.IsNullOrWhiteSpace(authToken)) { authToken = context.Request.Params["apikey"]; } if (!string.IsNullOrWhiteSpace(authToken)) { var userLoginService = new UserLoginService(new Rock.Data.RockContext()); var userLogin = userLoginService.Queryable().Where(u => u.ApiKey == authToken).FirstOrDefault(); if (userLogin != null) { var identity = new GenericIdentity(userLogin.UserName); var principal = new GenericPrincipal(identity, null); context.User = principal; } } } var currentUser = UserLoginService.GetCurrentUser(); Person currentPerson = currentUser != null ? currentUser.Person : null; try { HttpFileCollection hfc = context.Request.Files; HttpPostedFile uploadedFile = hfc.AllKeys.Select(fk => hfc[fk]).FirstOrDefault(); // No file or no data? No good. if (uploadedFile == null || uploadedFile.ContentLength == 0) { throw new Rock.Web.FileUploadException("No File Specified", System.Net.HttpStatusCode.BadRequest); } // Check to see if this is a BinaryFileType/BinaryFile or just a plain content file bool isBinaryFile = context.Request.QueryString["isBinaryFile"].AsBoolean(); if (isBinaryFile) { ProcessBinaryFile(context, uploadedFile, currentPerson); } else { if (!context.User.Identity.IsAuthenticated) { throw new Rock.Web.FileUploadException("Must be logged in", System.Net.HttpStatusCode.Forbidden); } else { ProcessContentFile(context, uploadedFile); } } } catch (Rock.Web.FileUploadException fex) { ExceptionLogService.LogException(fex, context); context.Response.TrySkipIisCustomErrors = true; context.Response.StatusCode = ( int )fex.StatusCode; context.Response.Write(fex.Detail); } catch (Exception ex) { ExceptionLogService.LogException(ex, context); context.Response.StatusCode = ( int )System.Net.HttpStatusCode.InternalServerError; context.Response.Write("error: " + ex.Message); } }
/// <summary> /// Gets the file bytes /// </summary> /// <param name="context">The context.</param> /// <param name="uploadedFile">The uploaded file.</param> /// <returns></returns> public virtual Stream GetFileContentStream(HttpContext context, HttpPostedFile uploadedFile) { // NOTE: GetFileBytes can get overridden by a child class (ImageUploader.ashx.cs for example) return(uploadedFile.InputStream); }