protected void UploadButton_Click(object sender, EventArgs e) { var pathFile = Server.MapPath("~/uploads/deliveries/post_office/" + Path.GetFileName(FileUpload.FileName)); if (FileUpload.HasFile) { // Nếu tồn tại file củ thì xóa đi File.Delete(pathFile); FileUpload.SaveAs(pathFile); var check = checkExcelStucture(pathFile); if (check) { importExcel(pathFile); UploadStatusLabel.Text = "Đã nhập import thành công file " + FileUpload.FileName; } else { UploadStatusLabel.Text = String.Format("Câu trúc file {0} không đúng quá quy định ", FileUpload.FileName); } // Xóa file sau khi hoàn thành File.Delete(pathFile); } else { UploadStatusLabel.Text = "Có vấn đề trong việc import file " + FileUpload.FileName; } FileUpload.Dispose(); LoadData(); }
private bool bSaveFile() { bool bReturn = false; try { string xFileName = ""; byte[] xFileByte = null; FileUpload file = this.fileUplaod;// ((FileUpload)((C1.Web.C1WebGrid.C1GridItem)this.grdList.Items[i]).FindControl("fileUplaod")); if (file.FileBytes.Length > 0) { xFileName = file.FileName.Replace(" ", "_").Replace("..", "_"); xFileByte = file.FileBytes; SBROKER.GetString("CLT.WEB.BIZ.LMS.EDUM.vp_a_edumng_md", "SetFileAtt", LMS_SYSTEM.MANAGE, "CLT.WEB.UI.LMS.MANAGE", xFileByte, xFileName, txtID.Text.ToUpper().Replace("'", "''")); } file.Dispose(); bReturn = true; } catch (Exception ex) { bReturn = false; } return(bReturn); }
/// <summary> /// 上传文件 /// </summary> /// <param name="files">FileUpload控件</param> /// <returns></returns> public static void FileUpLoad(FileUpload files, ref string filepath) { //filepath = ""; if (files.FileName != "") { string ext = EKFileUpload.getExtend(files.FileName); if (!EKFileUpload.CheckExt(ext)) { EKMessageBox.Show("文件上传失败,文件格式不允许上传!"); } else { if (filepath == "") { string FileName = "/" + MS_ConfigBLL.UploadPath + "/" + EKFileUpload.getMyPath() + EKFileUpload.createFileName() + "." + ext; string SaveFile = EKFileUpload.FilePath + FileName; EKFileUpload.doCreatrDir(SaveFile); files.SaveAs(SaveFile); filepath = FileName; } else { string SaveFile = filepath + "\\" + files.FileName; files.SaveAs(SaveFile); } files.Dispose(); } } }
public string UploadFile(FileUpload Fupload, string str_mulu, string str_maxid) { //文件上传 string str_ParentFolder; string str_NewFileName, str_OriginalFileName; try { if (Fupload.PostedFile.FileName == "") { return(","); } str_ParentFolder = Server.MapPath(".\\" + str_mulu + "\\"); //创建文件夹 if (!Directory.Exists(str_ParentFolder)) { Directory.CreateDirectory(str_ParentFolder); if (!Directory.Exists(str_ParentFolder)) { return(""); } } string extname; extname = Fupload.FileName.Substring(Fupload.FileName.LastIndexOf(".") + 1).ToUpper(); str_OriginalFileName = Fupload.FileName; str_NewFileName = str_maxid + "." + extname; //判断上传课件类型,大小 string str_sql = "select url from t_dict where flm = 8 and bm in (4,5)"; DataView dv = DBFun.dataView(str_sql); string str_UploadFileType = dv.Table.Rows[0]["url"].ToString(); string str_UploadFileSize = dv.Table.Rows[1]["url"].ToString(); if (str_UploadFileType.IndexOf(extname.ToLower()) == -1) { Response.Write("<script>alert('不允许上传 " + extname + " 类型的文件!');</script>"); return(""); } if (Convert.ToDecimal(str_UploadFileSize) * Convert.ToDecimal(1024) < Fupload.PostedFile.ContentLength) { Response.Write("<script>alert('不允许上传超过 " + str_UploadFileSize + "KB的文件!');</script>"); return(""); } Fupload.PostedFile.SaveAs(str_ParentFolder + "\\" + str_NewFileName); Session["FilePath"] = str_ParentFolder + "\\" + str_NewFileName; Fupload.Dispose(); return(str_OriginalFileName + "," + str_NewFileName); } catch { File.Delete(Session["FilePath"].ToString()); Response.Write("<script>alert('文件上传失败!');</script>"); return(""); } }
/// <summary> /// 保存文件 /// </summary> /// <param name="fu">上传文件对象</param> /// <param name="IsImage">是否图片</param> /// <returns>成功/失败</returns> public bool SaveFile(FileUpload fu, bool IsImage) { bool rBool = false; rBool = SaveFile(fu.PostedFile, IsImage); fu.Dispose(); return(rBool); }
public void HandleImageUpload(FileUpload FileData, string Path, int OrgHeight, int ThumbHeight) { if (!Directory.Exists(Path)) { Directory.CreateDirectory(@"" + Path); } ImageCodecInfo iciJpegCodec = null; EncoderParameter epQuality = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L); ImageCodecInfo[] iciCodecs = ImageCodecInfo.GetImageEncoders(); EncoderParameters epParameters = new EncoderParameters(1); epParameters.Param[0] = epQuality; for (int i = 0; i < iciCodecs.Length; i++) { if (iciCodecs[i].MimeType == "image/jpeg") { iciJpegCodec = iciCodecs[i]; break; } } // Create a bitmap of the content of the fileUpload control in memory Bitmap originalBMP = new Bitmap(FileData.FileContent); string strFilename = FileData.FileName.Substring(0, FileData.FileName.LastIndexOf(".")) + ".jpg"; if (OrgHeight < originalBMP.Height) { (ImageResizing(originalBMP, OrgHeight, -1)).Save(Path + strFilename, iciJpegCodec, epParameters); } else { originalBMP.Save(Path + strFilename, iciJpegCodec, epParameters); } float tmpwidth = ((float)ThumbHeight / (float)originalBMP.Height) * (float)originalBMP.Width; if (tmpwidth <= 150) { (ImageResizing(originalBMP, ThumbHeight, -1)).Save(Path + "t_" + strFilename, iciJpegCodec, epParameters); } else { (ImageResizing(originalBMP, -1, 150)).Save(Path + "t_" + strFilename, iciJpegCodec, epParameters); } FileData.SaveAs(Path + "org_" + FileData.FileName); // Once finished with the bitmap objects, we deallocate them. originalBMP.Dispose(); FileData.Dispose(); }
protected void btn_save_Click(object sender, EventArgs e) { try { string xFileName = ""; byte[] xFileByte = null; int xChkSel = 0; int xCntSel = 0; for (int i = 0; i < this.grdList.Items.Count; i++) { if (((HtmlInputCheckBox)((C1.Web.C1WebGrid.C1GridItem) this.grdList.Items[i]).FindControl("chk_sel")).Checked) { xChkSel++; FileUpload file = ((FileUpload)((C1.Web.C1WebGrid.C1GridItem) this.grdList.Items[i]).FindControl("fileUplaod")); if (file.FileBytes.Length > 0) { xCntSel++; xFileName = file.FileName.Replace(" ", "_").Replace("..", "_"); xFileByte = file.FileBytes; SBROKER.GetString("CLT.WEB.BIZ.LMS.EDUM.vp_a_edumng_md", "SetFileAtt", LMS_SYSTEM.MANAGE, "CLT.WEB.UI.LMS.EDUM.vp_a_eduming_issuing_wpg", xFileByte, xFileName, grdList.DataKeys[i].ToString()); } file.Dispose(); } } if (xCntSel > 0) { ScriptHelper.Page_Alert(this.Page, MsgInfo.GetMsg("A001", new string[] { "사진" }, new string[] { "Photo" }, Thread.CurrentThread.CurrentCulture)); GC.Collect(); //BindGrdList(1, ""); } else if (xChkSel == 0) { ScriptHelper.Page_Alert(this, CLT.WEB.UI.COMMON.BASE.MsgInfo.GetMsg("A047", new string[] { "" }, new string[] { "" }, System.Threading.Thread.CurrentThread.CurrentCulture)); } else { ScriptHelper.Page_Alert(this, CLT.WEB.UI.COMMON.BASE.MsgInfo.GetMsg("A003", new string[] { "사진" }, new string[] { "Photo" }, System.Threading.Thread.CurrentThread.CurrentCulture)); } } catch (Exception ex) { base.NotifyError(ex); } }
private void UploadSoft(FileUpload updUploadFile, Label lblErr, out string savedFileName) { savedFileName = ""; try { string strRootPath = Server.MapPath("/Upload/"); //Create directory string dir_name = DateTime.Now.ToString("yyyyMMdd"); if (!System.IO.Directory.Exists(strRootPath + dir_name)) { Directory.CreateDirectory(strRootPath + dir_name); } //Fix the relative path to physical path to upload string strExt = Path.GetExtension(updUploadFile.PostedFile.FileName).ToLower().Replace(".", ""); savedFileName = dir_name + "/" + updUploadFile.FileName; string strFilePath = strRootPath + savedFileName; if ((strExt == "rar") || (strExt == "zip")) { // If not exist a file then load this file if (!File.Exists(strFilePath)) { // Create thumbnail image updUploadFile.SaveAs(strFilePath); updUploadFile.Dispose(); lblErr.Text = "File <" + savedFileName + "> upload thành công. "; } // If existed or save process has error then alert message else { lblErr.Text = "File <" + savedFileName + "> đã tồn tại, vui lòng đổi tên!."; savedFileName = ""; } } else { lblErr.Text = "Chỉ được upload file định dạng rar,zip"; savedFileName = ""; } } catch (Exception ex) { lblErr.Text = ex.Message; savedFileName = ""; } }
public static SaveFileResult SaveFile(FileUpload FileUpload, string filename, string SaveFilePath, int MaxKBSize, params string[] Extensions) { SaveFileResult result = null; result = new SaveFileResult(); if ((FileUpload != null) && FileUpload.HasFile) { if (string.IsNullOrEmpty((SaveFilePath ?? "").Trim())) { result.Msg = "未設定儲存路徑"; return(result); } if ((MaxKBSize > 0) && (FileUpload.PostedFile.ContentLength > (MaxKBSize * 0x400))) { result.Msg = "超出大小限制"; return(result); } if (Extensions.Length > 0) { bool flag = false; foreach (string str in Extensions) { if (Path.GetExtension(FileUpload.FileName).ToLower() == ("." + str.ToLower())) { flag = true; break; } } if (!flag) { result.Msg = "不是允許的副檔名"; return(result); } } if (Strings.Right(SaveFilePath, 1) != "/") { SaveFilePath = SaveFilePath + "/"; } SetFolder(SaveFilePath); string str2 = filename + Path.GetExtension(FileUpload.FileName); string str3 = HttpContext.Current.Server.MapPath(SaveFilePath + str2); FileUpload.SaveAs(str3); FileUpload.Dispose(); result.Result = true; result.Msg = SaveFilePath + str2; } return(result); }
void IDisposable.Dispose() { _strAllowType = null; _strButtonSaveCSSClass = null; _strButtonSaveText = null; _strPicSavedName = null; _strPicSavedPath = null; _strPicSavePath = null; _strSuccessfulText = null; _strPicThumbSavedName = null; _strPicThumbSavedPath = null; _strPicThumbSavePath = null; _strWatermarkImage = null; _strWatermarkText = null; _fileUpload.Dispose(); _btnSave.Dispose(); _fontWatermarkFont.Dispose(); }
public SyncCompleteResponse Packet_Complete(SyncCompleteRequest complete) { try { FileUpload upload = _uploads.ContainsKey(complete.UploadID) ? _uploads[complete.UploadID] : null; if (upload == null) { return new SyncCompleteResponse() { Success = false } } ; _uploads.Remove(complete.UploadID); lock (upload) { upload.FinalWrite(); SyncRequest obj = upload.GetContext <SyncRequest>(); string fileName = upload.TargetPath; upload.Dispose(); SessionData session = SessionData.GetOrCreate(obj.SessionID); session.UpdatedFile(obj.FileID); return(new SyncCompleteResponse() { Success = true }); } } catch (Exception ex) { return(new SyncCompleteResponse() { Success = false, Message = "Failed due to exception:" + ex.Message }); } }
void btn_Siganture_Click(object sender, EventArgs e) { FileUpload f = (FileUpload)this.FindControl("F"); if (f.HasFile == false) { return; } try { System.IO.File.Delete(BP.SystemConfig.PathOfWebApp + "/DataUser/Siganture/T.jpg"); f.SaveAs(BP.SystemConfig.PathOfWebApp + "/DataUser/Siganture/T.jpg"); System.Drawing.Image img = System.Drawing.Image.FromFile(BP.SystemConfig.PathOfWebApp + "/DataUser/Siganture/T.jpg"); if (img.Width != 90 || img.Height != 30) { img.Dispose(); throw new Exception("您上传的图片不符合要求高度=30px 宽度=90px 的要求。"); } img.Dispose(); } catch (Exception ex) { this.Alert(ex.Message); return; } f.SaveAs(BP.SystemConfig.PathOfWebApp + "/DataUser/Siganture/" + WebUser.No + ".jpg"); f.SaveAs(BP.SystemConfig.PathOfWebApp + "/DataUser/Siganture/" + WebUser.Name + ".jpg"); f.PostedFile.InputStream.Close(); f.PostedFile.InputStream.Dispose(); f.Dispose(); this.Response.Redirect(this.Request.RawUrl, true); //this.Alert("保存成功。"); }
/// <summary> /// 保存文件 /// </summary> /// <param name="fu">上传文件对象</param> /// <param name="IsImage">是否邮件</param> public bool SaveFile(FileUpload fu) { if (fu.HasFile) { string fileContentType = fu.PostedFile.ContentType; string name = fu.PostedFile.FileName; // 客户端文件路径 FileInfo file = new FileInfo(name); _fileType = fu.PostedFile.ContentType; _fileSize = fu.PostedFile.ContentLength; bool isfileTypeImages = false; if (fileContentType == "image/x-png" || fileContentType == "image/png" || fileContentType == "image/bmp" || fileContentType == "image/gif" || fileContentType == "image/pjpeg") { isfileTypeImages = true; } //检测文件扩展名是否正确 var ImgExtention = file.Extension.Substring(1).ToLower(); if (ImgExtention != "gif" && ImgExtention != "jpg" && ImgExtention != "jpeg" && ImgExtention != "png") { _errorMsg = string.Format("文件扩展名不符合系统需求:{0}", "gif|jpg|jpeg|png"); fu.Dispose(); return(false); } if (_fileSize / 1024 > 2048) { _errorMsg = string.Format("上传文件超过系统允许大小:{0}K", "2048"); fu.Dispose(); return(false); } _fileName = file.Name; // 文件名称 _newFileName = CreateFileName() + file.Extension; _webFilePath = HttpContext.Current.Server.MapPath(_path + _newFileName); // 服务器端文件路径 if (isfileTypeImages) { //检查文件是否存在 if (!File.Exists(_webFilePath)) { try { fu.SaveAs(_webFilePath); // 使用 SaveAs 方法保存文件 // 只有上传完了,才能获取图片大小 if (File.Exists(_webFilePath)) { System.Drawing.Image originalImage = System.Drawing.Image.FromFile(_webFilePath); try { _fileHeight = originalImage.Height; _fileWidth = originalImage.Width; } finally { originalImage.Dispose(); } } _errorMsg = string.Format("提示:文件“{0}”成功上传,文件类型为:{1},文件大小为:{2}B", _newFileName, fu.PostedFile.ContentType, fu.PostedFile.ContentLength); fu.Dispose(); return(true); } catch (Exception ex) { _errorMsg = "提示:文件上传失败,失败原因:" + ex.Message; } } else { _errorMsg = "提示:文件已经存在,请重命名后上传"; } } else { //上传文件 //检查文件是否存在 if (!File.Exists(_webFilePath)) { try { fu.SaveAs(_webFilePath); // 使用 SaveAs 方法保存文件 _errorMsg = string.Format("提示:文件“{0}”成功上传,文件类型为:{1},文件大小为:{2}B", _newFileName, fu.PostedFile.ContentType, fu.PostedFile.ContentLength); fu.Dispose(); return(true); } catch (Exception ex) { _errorMsg = "提示:文件上传失败,失败原因:" + ex.Message; } } else { _errorMsg = "提示:文件已经存在,请重命名后上传"; } } } fu.Dispose(); return(false); }
public string UploadFile(FileUpload Fupload, string str_mulu, string str_maxid) { //文件上传 string str_ParentFolder; string str_NewFileName, str_OriginalFileName; try { if (Fupload.PostedFile.FileName == "") { return(","); } str_ParentFolder = Server.MapPath(".\\" + str_mulu + "\\"); //创建以教师id+课程id为名的文件夹 //string str_TeacherId, str_CourseId, str_FileType; //str_TeacherId = Session["TeacherID"].ToString(); //str_CourseId = ddlist_Course.SelectedValue; //str_FileType = ddlist_Type.SelectedValue; //dir = str_TeacherId + "_" + str_CourseId; if (!Directory.Exists(str_ParentFolder)) { Directory.CreateDirectory(str_ParentFolder); if (!Directory.Exists(str_ParentFolder)) { return(""); } } //Random rd = new Random(); string extname; extname = Fupload.FileName.Substring(Fupload.FileName.LastIndexOf(".") + 1).ToUpper(); str_OriginalFileName = Fupload.FileName; str_NewFileName = str_maxid + "." + extname; //判断上传课件类型 string str_sql = "select url from t_dict where flm=8 and bm in (7,8)"; DataView dv = DBFun.dataView(str_sql); string str_UploadFileType = dv.Table.Rows[0]["url"].ToString(); string str_UploadFileSize = dv.Table.Rows[1]["url"].ToString(); if (str_UploadFileType.IndexOf(extname.ToLower()) == -1) { Response.Write("<script>alert('不允许上传 " + extname + " 类型的文件!');</script>"); return(""); } if (Convert.ToInt16(str_UploadFileSize) * 1024 < Fupload.PostedFile.ContentLength) { Response.Write("<script>alert('不允许上传超过 " + str_UploadFileSize + " K的文件!');</script>"); return(""); } //string str_sql; //str_sql = " Select iif(Max(FileID),Max(FileID)+1,1) " + // " From CourseTeacher " + // " Where (CourseID=" + str_CourseId + ") AND (TeacherID = " + str_TeacherId + ");"; //int i_MaxID = (int)DBFun.ExecuteScalar(str_sql); ///*判断是否更名*/ //if (tbx_Rename.Visible & tbx_Rename.Text.Trim() != "") //{ // filename = tbx_Rename.Text.Trim() + "." + extname; //} //else //{ // filename = Fupload.FileName; //} //if (File.Exists(str_ParentFolder + dir + "\\" + filename)) //{ // Response.Write("<script>alert('文件 " + filename + " 已存在!');</script>"); // return ""; //} Fupload.PostedFile.SaveAs(str_ParentFolder + "\\" + str_NewFileName); //Session["FilePath"] = str_ParentFolder + "\\" + filename; //str_sql = "Insert Into CourseTeacher (CourseID ,TeacherID ,FileID,FilePath,FileName,FileType,Chapter,CreateDate) Values (" + // str_CourseId + "," + str_TeacherId + "," + i_MaxID.ToString() + ",'" + dir + "','" + filename + "','" + // str_FileType + "','" + tbx_Chapter.Text + "','" + System.DateTime.Today.ToLongDateString() + "')"; //DBFun.ExecuteUpdate(str_sql); Fupload.Dispose(); return(str_OriginalFileName + "," + str_NewFileName); //用文件名上传的方式 //if (tbx_Research.Text != "") //{ // extname = System.IO.Path.GetExtension(tbx_Research.Text); // filename = dir + "\\" + DateTime.Now.ToString("yyyyMM") + rd.Next(1000).ToString() + extname; // System.IO.File.Copy(tbx_Research.Text, Server.MapPath(".\\kejian\\") + filename); // return filename; //} //return ""; } catch { File.Delete(Session["FilePath"].ToString()); Response.Write("<script>alert('文件上传失败!');</script>"); return(""); } }
public string UploadFile(FileUpload Fupload) { //文件上传 string str_ParentFolder; string dir; string filename; try { if (Fupload.PostedFile.FileName == "") { return(""); } str_ParentFolder = Server.MapPath(@"..\app_data\"); //创建以教师id+课程id为名的文件夹 if (!Directory.Exists(str_ParentFolder)) { Directory.CreateDirectory(str_ParentFolder); if (!Directory.Exists(str_ParentFolder)) { return(""); } } string extname; if (Fupload.PostedFile.FileName != "") { extname = Fupload.FileName.Substring(Fupload.FileName.LastIndexOf(".") + 1).ToUpper(); //判断上传课件类型 string str_UploadFileType = "xls"; if (str_UploadFileType.IndexOf(extname.ToLower()) == -1) { Response.Write("<script>alert('不允许上传 " + extname + " 类型的文件!');</script>"); return(""); } string str_sql; /*判断是否更名*/ filename = "lqjg.xls"; Fupload.PostedFile.SaveAs(str_ParentFolder + filename); str_sql = "select * from [lqjg$] "; DataTable dt = ExcelManager.GetXlsDataTable(str_ParentFolder + filename, str_sql); int j = 0, k = 0; for (int i = 0; i < dt.Rows.Count; i++) { str_sql = "select count(*) from lqjg where 考生号 ='" + dt.Rows[i][0].ToString() + "'"; if ((int)DBFun.ExecuteScalar(str_sql) == 0) { str_sql = string.Format("insert into lqjg (考生号,身份证号,姓名,性别,系别,专业,是否寄出通知书) values ('{0}','{1}','{2}','{3}','{4}','{5}','{6}')", dt.Rows[i][0].ToString(), dt.Rows[i][1].ToString(), dt.Rows[i][2].ToString(), dt.Rows[i][3].ToString(), dt.Rows[i][4].ToString(), dt.Rows[i][5].ToString(), dt.Rows[i][6].ToString()); j++; } else { str_sql = string.Format("update lqjg set 身份证号='{1}',姓名='{2}',性别='{3}',系别='{4}',专业='{5}',是否寄出通知书='{6}' where 考生号='{0}'", dt.Rows[i][0].ToString(), dt.Rows[i][1].ToString(), dt.Rows[i][2].ToString(), dt.Rows[i][3].ToString(), dt.Rows[i][4].ToString(), dt.Rows[i][5].ToString(), dt.Rows[i][6].ToString()); k++; } if (!DBFun.ExecuteUpdate(str_sql)) { return(""); } } str_sql = "select count(*) from lqjg where 考生号 <> ''"; lbl_result.Text = "数据库中共有记录 " + DBFun.ExecuteScalar(str_sql).ToString() + " 条,本次新增了 " + j.ToString() + " 条记录,更新了 " + k.ToString() + " 条记录"; Fupload.Dispose(); return(filename); } //用文件名上传的方式 //if (tbx_Research.Text != "") //{ // extname = System.IO.Path.GetExtension(tbx_Research.Text); // filename = dir + "\\" + DateTime.Now.ToString("yyyyMM") + rd.Next(1000).ToString() + extname; // System.IO.File.Copy(tbx_Research.Text, Server.MapPath(".\\kejian\\") + filename); // return filename; //} return(""); } catch { //File.Delete(Session["FilePath"].ToString()); //Response.Write("<script>alert('文件上传失败!');</script>"); return(""); } }
public string UploadFile(FileUpload Fupload, string str_mulu, string str_appNo) { //文件上传 string str_ParentFolder; //上传目录 string str_NewFileName, str_OriginalFileName; //文件新名,原始名 string extname; //文件扩展名 try { if (Fupload.PostedFile.FileName == "") { return(","); } str_ParentFolder = Server.MapPath(".\\" + str_mulu + "\\"); if (!Directory.Exists(str_ParentFolder)) { Directory.CreateDirectory(str_ParentFolder); if (!Directory.Exists(str_ParentFolder)) { return(""); } } str_OriginalFileName = Fupload.FileName; extname = str_OriginalFileName.Substring(str_OriginalFileName.LastIndexOf(".") + 1).ToUpper(); str_NewFileName = str_appNo + "." + extname; //判断上传文件类型 string str_UploadFileType = ConfigurationManager.AppSettings.Get("UploadFileType"); //string str_UploadFileSize = dv.Table.Rows[1]["url"].ToString(); if (str_UploadFileType.IndexOf(extname.ToLower()) == -1) { Response.Write("<script>alert('不允许上传 " + extname + " 类型的文件!');</script>"); return(""); } //if (Convert.ToDecimal(str_UploadFileSize) * Convert.ToDecimal(1024) < Fupload.PostedFile.ContentLength) //{ // Response.Write("<script>alert('不允许上传超过 " + str_UploadFileSize + "KB的文件!');</script>"); // return ""; //} //string str_sql; //str_sql = " Select iif(Max(FileID),Max(FileID)+1,1) " + // " From CourseTeacher " + // " Where (CourseID=" + str_CourseId + ") AND (TeacherID = " + str_TeacherId + ");"; //int i_MaxID = (int)DBFun.ExecuteScalar(str_sql); ///*判断是否更名*/ //if (tbx_Rename.Visible & tbx_Rename.Text.Trim() != "") //{ // filename = tbx_Rename.Text.Trim() + "." + extname; //} //else //{ // filename = Fupload.FileName; //} //if (File.Exists(str_ParentFolder + dir + "\\" + filename)) //{ // Response.Write("<script>alert('文件 " + filename + " 已存在!');</script>"); // return ""; //} Fupload.PostedFile.SaveAs(str_ParentFolder + "\\" + str_NewFileName); ViewState["FilePath"] = str_ParentFolder + "\\" + str_NewFileName; //str_sql = "Insert Into CourseTeacher (CourseID ,TeacherID ,FileID,FilePath,FileName,FileType,Chapter,CreateDate) Values (" + // str_CourseId + "," + str_TeacherId + "," + i_MaxID.ToString() + ",'" + dir + "','" + filename + "','" + // str_FileType + "','" + tbx_Chapter.Text + "','" + System.DateTime.Today.ToLongDateString() + "')"; //DBFun.ExecuteUpdate(str_sql); Fupload.Dispose(); return(str_OriginalFileName + "," + str_NewFileName); //用文件名上传的方式 //if (tbx_Research.Text != "") //{ // extname = System.IO.Path.GetExtension(tbx_Research.Text); // filename = dir + "\\" + DateTime.Now.ToString("yyyyMM") + rd.Next(1000).ToString() + extname; // System.IO.File.Copy(tbx_Research.Text, Server.MapPath(".\\kejian\\") + filename); // return filename; //} //return ""; } catch { File.Delete(ViewState["FilePath"].ToString()); Response.Write("<script>alert('文件上传失败!');</script>"); return(""); } }
public string UploadFile(FileUpload Fupload) { //文件上传 string str_ParentFolder; string filename; str_ParentFolder = Server.MapPath(@"..\app_data\"); /*判断是否更名*/ filename = "zhuanjia.xls"; try { //使用已有对应关系文件 if (cbx_upload.Checked) { if (!File.Exists(str_ParentFolder + filename)) { return("文件不存在!"); } } //上传新的对应关系文件 else { if (Fupload.PostedFile.FileName == "") { return("请选择要上传的数据!"); } //创建文件夹 if (!Directory.Exists(str_ParentFolder)) { Directory.CreateDirectory(str_ParentFolder); if (!Directory.Exists(str_ParentFolder)) { return("创建文件夹失败!"); } } if (Fupload.PostedFile.FileName != "") { string extname = Fupload.FileName.Substring(Fupload.FileName.LastIndexOf(".") + 1).ToUpper(); //判断上传类型 string str_UploadFileType = "xls"; if (str_UploadFileType.IndexOf(extname.ToLower()) == -1) { return("<script>alert('不允许上传 " + extname + " 类型的文件!');</script>"); } Fupload.PostedFile.SaveAs(str_ParentFolder + filename); } } str_sql = "select * from [sheet1$] "; DataTable dt = ExcelManager.GetXlsDataTable(str_ParentFolder + filename, str_sql); int j = 0, k = 0; //string str_sfzh = ""; //for (int i = 0; i < dt.Rows.Count; i++) //{ // str_sfzh = dt.Rows[i][3].ToString().Trim(); // if (!CommFun.IsCardCode(str_sfzh)) // { // i = i + 2; // return "第" + i.ToString() + "行身份证号错误!"; // } // //if (dt.Rows[i][0].ToString().Trim() == "") // //{ // // i = i + 2; // // return "第" + i.ToString() + "行单位名称为空,请删除该行!"; // //} //} for (int i = 0; i < dt.Rows.Count; i++) { str_sql = "select count(*) from t_yszj where appyear=year(date()) and sfzh ='" + dt.Rows[i][3].ToString() + "'"; string str_pwd = dt.Rows[i][3].ToString().Trim(); //if (!IsCardCode(str_pwd)) //{ // i=i+1; // return "第"+i.ToString()+"行身份证号错误!"; //} if (str_pwd.Length == 18) { str_pwd = str_pwd.Substring(8, 6); } else { str_pwd = str_pwd.Substring(6, 6); } str_pwd = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str_pwd, "MD5"); if ((int)DBFun.ExecuteScalar(str_sql) == 0) { str_sql = string.Format("insert into t_yszj (gzdw,username,xingbie,sfzh,csrq,xueli,byxx," + "bysj,sxzy,zc,qdzgsj,xcszyly,sxzyly,pwd,zjdm) values " + "('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}',{14},'{15}')", dt.Rows[i][0].ToString(), dt.Rows[i][1].ToString(), dt.Rows[i][2].ToString(), dt.Rows[i][3].ToString(), dt.Rows[i][4].ToString(), dt.Rows[i][5].ToString(), dt.Rows[i][6].ToString(), dt.Rows[i][7].ToString(), dt.Rows[i][8].ToString(), dt.Rows[i][9].ToString(), dt.Rows[i][10].ToString(), dt.Rows[i][11].ToString(), dt.Rows[i][12].ToString(), str_pwd, dt.Rows[i][13].ToString()); j++; } else { str_sql = string.Format("update t_yszj set gzdw='{0}',username='******',xingbie='{2}',sfzh='{3}',csrq='{4}',xueli='{5}'," + " byxx='{6}',bysj='{7}',sxzy='{8}',zc='{9}',qdzgsj='{10}',xcszyly='{11}',sxzyly='{12}',pwd = '{13}',zjdm = '{14}' " + " where appyear=year(date()) and sfzh='{15}'", dt.Rows[i][0].ToString(), dt.Rows[i][1].ToString(), dt.Rows[i][2].ToString(), dt.Rows[i][3].ToString(), dt.Rows[i][4].ToString(), dt.Rows[i][5].ToString(), dt.Rows[i][6].ToString(), dt.Rows[i][7].ToString(), dt.Rows[i][8].ToString(), dt.Rows[i][9].ToString(), dt.Rows[i][10].ToString(), dt.Rows[i][11].ToString(), dt.Rows[i][12].ToString(), str_pwd, dt.Rows[i][13].ToString(), dt.Rows[i][3].ToString()); k++; } if (!DBFun.ExecuteUpdate(str_sql)) { return("系统错误"); } } str_sql = "select count(*) from t_yszj where appyear=year(date()) and sfzh <> ''"; lbl_result.Visible = true; lbl_result.Text = "数据库中共有记录 " + DBFun.ExecuteScalar(str_sql).ToString() + " 条,本次新增了 " + j.ToString() + " 条记录,更新了 " + k.ToString() + " 条记录"; Fupload.Dispose(); if (lbl_type.Text == "2") { str_sql = " delete from zjry "; //DBFun.ExecuteUpdate(str_sql); //str_sql = " insert into zjry (appyear,zj_sfzh,cpry_sfzh,fs_sftj) " + // " select 2,pszj.sfzh,ej_cpry.sfzh,'false' from pszj,ej_cpry where pszj.flag = 2;"; if (!DBFun.ExecuteUpdate(str_sql)) { return("上传失败"); } } return("上传成功"); //用文件名上传的方式 //if (tbx_Research.Text != "") //{ // extname = System.IO.Path.GetExtension(tbx_Research.Text); // filename = dir + "\\" + DateTime.Now.ToString("yyyyMM") + rd.Next(1000).ToString() + extname; // System.IO.File.Copy(tbx_Research.Text, Server.MapPath(".\\kejian\\") + filename); // return filename; //} //return ""; } catch (IOException e) { return(e.Message); } catch (Exception e) { return(e.Message); } }
public string UploadFile(FileUpload Fupload) { //文件上传 string str_ParentFolder; string filename; try { if (Fupload.PostedFile.FileName == "") { return("请选择要上传的数据!"); } str_ParentFolder = Server.MapPath(@"..\app_data\"); //创建文件夹 if (!Directory.Exists(str_ParentFolder)) { Directory.CreateDirectory(str_ParentFolder); if (!Directory.Exists(str_ParentFolder)) { return("创建文件夹失败!"); } } string extname; if (Fupload.PostedFile.FileName != "") { extname = Fupload.FileName.Substring(Fupload.FileName.LastIndexOf(".") + 1).ToUpper(); //判断上传类型 string str_UploadFileType = "xls"; if (str_UploadFileType.IndexOf(extname.ToLower()) == -1) { return("<script>alert('不允许上传 " + extname + " 类型的文件!');</script>"); } string str_sql; /*判断是否更名*/ filename = "zhuanjia.xls"; Fupload.PostedFile.SaveAs(str_ParentFolder + filename); str_sql = "select * from [sheet1$] "; DataTable dt = ExcelManager.GetXlsDataTable(str_ParentFolder + filename, str_sql); int j = 0, k = 0; for (int i = 0; i < dt.Rows.Count; i++) { str_sql = "select count(*) from pszj where flag = 2 and sfzh ='" + dt.Rows[i][3].ToString() + "'"; string str_pwd = dt.Rows[i][3].ToString().Substring(dt.Rows[i][3].ToString().Length - 6); str_pwd = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str_pwd, "MD5"); if ((int)DBFun.ExecuteScalar(str_sql) == 0) { str_sql = string.Format("insert into pszj (gzdw,username,xingbie,sfzh,csrq,xueli,byxx," + "bysj,sxzy,zc,qdzgsj,xcszyly,sxzyly,pwd,flag) values " + "('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}',2)", dt.Rows[i][0].ToString(), dt.Rows[i][1].ToString(), dt.Rows[i][2].ToString(), dt.Rows[i][3].ToString(), dt.Rows[i][4].ToString(), dt.Rows[i][5].ToString(), dt.Rows[i][6].ToString(), dt.Rows[i][7].ToString(), dt.Rows[i][8].ToString(), dt.Rows[i][9].ToString(), dt.Rows[i][10].ToString(), dt.Rows[i][11].ToString(), dt.Rows[i][12].ToString(), str_pwd); j++; } else { str_sql = string.Format("update pszj set gzdw='{0}',username='******',xingbie='{2}',sfzh='{3}',csrq='{4}',xueli='{5}'," + " byxx='{6}',bysj='{7}',sxzy='{8}',zc='{9}',qdzgsj='{10}',xcszyly='{11}',sxzyly='{12}',pwd = '{13}' " + " where flag = 2 and sfzh='{14}'", dt.Rows[i][0].ToString(), dt.Rows[i][1].ToString(), dt.Rows[i][2].ToString(), dt.Rows[i][3].ToString(), dt.Rows[i][4].ToString(), dt.Rows[i][5].ToString(), dt.Rows[i][6].ToString(), dt.Rows[i][7].ToString(), dt.Rows[i][8].ToString(), dt.Rows[i][9].ToString(), dt.Rows[i][10].ToString(), dt.Rows[i][11].ToString(), dt.Rows[i][12].ToString(), str_pwd, dt.Rows[i][3].ToString()); k++; } if (!DBFun.ExecuteUpdate(str_sql)) { return("系统错误"); } } str_sql = "select count(*) from pszj where flag = 2 and sfzh <> ''"; lbl_result.Visible = true; lbl_result.Text = "数据库中共有记录 " + DBFun.ExecuteScalar(str_sql).ToString() + " 条,本次新增了 " + j.ToString() + " 条记录,更新了 " + k.ToString() + " 条记录"; Fupload.Dispose(); return("上传成功"); } //用文件名上传的方式 //if (tbx_Research.Text != "") //{ // extname = System.IO.Path.GetExtension(tbx_Research.Text); // filename = dir + "\\" + DateTime.Now.ToString("yyyyMM") + rd.Next(1000).ToString() + extname; // System.IO.File.Copy(tbx_Research.Text, Server.MapPath(".\\kejian\\") + filename); // return filename; //} return(""); } catch (IOException e) { return(e.Message); } catch (Exception e) { return(e.Message); } }
public string UploadFile(FileUpload Fupload) { //文件上传 string str_ParentFolder; string filename; str_ParentFolder = Server.MapPath(@"..\app_data\"); /*判断是否更名*/ filename = "zhuanjia.xls"; try { //上传新的对应关系文件 if (Fupload.PostedFile.FileName == "") { return("请选择要上传的数据!"); } //创建文件夹 if (!Directory.Exists(str_ParentFolder)) { Directory.CreateDirectory(str_ParentFolder); if (!Directory.Exists(str_ParentFolder)) { return("创建文件夹失败!"); } } if (Fupload.PostedFile.FileName != "") { string extname = Fupload.FileName.Substring(Fupload.FileName.LastIndexOf(".") + 1).ToUpper(); //判断上传类型 string str_UploadFileType = "xls"; if (str_UploadFileType.IndexOf(extname.ToLower()) == -1) { return("<script>alert('不允许上传 " + extname + " 类型的文件!');</script>"); } Fupload.PostedFile.SaveAs(str_ParentFolder + filename); } string str_sql; str_sql = "select * from [sheet1$] "; DataTable dt = ExcelManager.GetXlsDataTable(str_ParentFolder + filename, str_sql); int j = 0, k = 0; for (int i = 0; i < dt.Rows.Count; i++) { str_sql = "select count(*) from t_pszj where appyear = year(date()) and sfzh ='" + dt.Rows[i][1].ToString() + "'"; string str_pwd = dt.Rows[i][1].ToString(); if (str_pwd.Length == 18) { str_pwd = str_pwd.Substring(8, 6); } else { str_pwd = str_pwd.Substring(6, 6); } str_pwd = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str_pwd, "MD5"); if ((int)DBFun.ExecuteScalar(str_sql) == 0) { str_sql = string.Format("insert into t_pszj (username,sfzh,pwd) values ('{0}','{1}','{2}')", dt.Rows[i][0].ToString(), dt.Rows[i][1].ToString(), str_pwd); j++; } else { str_sql = string.Format("update t_pszj set username='******',pwd='{1}' where appyear = year(date()) and sfzh='{2}'", dt.Rows[i][0].ToString(), str_pwd, dt.Rows[i][1].ToString()); k++; } if (!DBFun.ExecuteUpdate(str_sql)) { return("系统错误"); } } str_sql = "select count(*) from t_pszj where appyear = year(date()) and sfzh <> ''"; lbl_result.Visible = true; lbl_result.Text = "数据库中共有记录 " + DBFun.ExecuteScalar(str_sql).ToString() + " 条,本次新增了 " + j.ToString() + " 条记录,更新了 " + k.ToString() + " 条记录"; Fupload.Dispose(); //if (lbl_type.Text == "2") //{ // str_sql = " delete from zjry where flag = 2;"; // DBFun.ExecuteUpdate(str_sql); // str_sql = " insert into zjry (flag,zj_sfzh,cpry_sfzh,fs_sftj) " + // " select 2,pszj.sfzh,ej_cpry.sfzh,'false' from pszj,ej_cpry where pszj.flag = 2;"; // if (!DBFun.ExecuteUpdate(str_sql)) // { // return "上传失败"; // } //} return("上传成功"); } catch (IOException e) { return(e.Message); } catch (Exception e) { return(e.Message); } }
protected void UploadFile(FileUpload fuBulkUpload, string _filename) { // Delay for Progress Bar Thread.Sleep(5000); #region Add Item Programmatically DirectoryInfo dir = null; string extension, fileName = string.Empty; string path = string.Empty; string tableName = string.Empty; string getError = string.Empty; DataSet dataSet = new DataSet(); try { if (fuBulkUpload.HasFile) { string folderName = Guid.NewGuid().ToString(); string folderpath = Server.MapPath("~/sitecore/admin/template/" + folderName + "/"); string[] templatePathFiles = Directory.GetFiles(Server.MapPath("~/sitecore/admin/template/"), "*.xml", SearchOption.TopDirectoryOnly); List <string> templateFiles = new List <string>(); foreach (string template in templatePathFiles) { templateFiles.Add(Path.GetFileName(template).Substring(0, Path.GetFileName(template).LastIndexOf("."))); } ServerMapPath = folderpath; dir = Directory.CreateDirectory(folderpath); extension = Path.GetExtension(fuBulkUpload.FileName); fileName = fuBulkUpload.FileName.Substring(0, fuBulkUpload.FileName.LastIndexOf('.')); //if (fuBulkUpload.PostedFile.ContentLength > (maxFile * 1024)) // throw new Exception(string.Format("File size more than {0}MB, please upload file less than {1}MB.", maxFile, maxFile)); if (extension != ".csv") { throw new FormatException("Wrong File Format."); } if (_filename != fileName) { throw new Exception("Wrong File Upload. File Upload using filename " + _filename + ".csv or Try another File Upload.."); } if (!templateFiles.Contains(fileName)) { throw new Exception("Wrong File Name. No template name equals with this file name"); } path = folderpath + fuBulkUpload.FileName; fuBulkUpload.SaveAs(path); Data = LibraryHelpers.ConvertCSVToTable(path); UploadHelpers.MappedDataToDB(Data, folderpath.Replace(folderName, "") + "/" + fileName + ".xml", fileName); getError = UploadHelpers.GetErrorMessage(); if (getError == "ERROR") { litWarningError.Text = "Database is not Updated. Please make sure the Data is Valid."; Page.ClientScript.RegisterStartupScript(GetType(), "loadAlertWarning", "AlertWarningBottom()", true); } else { fuBulkUpload.Dispose(); Page.ClientScript.RegisterStartupScript(GetType(), "loadAlertSuccess", "AlertSuccessBottom()", true); } File.Delete(path); } } catch (FormatException fx) { litAlertError.Text = fx.Message; Page.ClientScript.RegisterStartupScript(GetType(), "loadAlertFailed", "AlertFailedBottom()", true); } catch (Exception ex) { litAlertError.Text = " " + ex.Message; Page.ClientScript.RegisterStartupScript(GetType(), "loadAlertFailed", "AlertFailedBottom()", true); } finally { if (!string.IsNullOrEmpty(path)) { File.Delete(path); } dir.Delete(); } #endregion }
public string UploadFile(FileUpload Fupload, TextBox tbx_Rename) { //文件上传 string str_ParentFolder; string dir; string filename; try { if (Fupload.PostedFile.FileName == "") { return(""); } str_ParentFolder = Server.MapPath(@"..\uploadfile\"); //创建以教师id+课程id为名的文件夹 if (!Directory.Exists(str_ParentFolder)) { Directory.CreateDirectory(str_ParentFolder); if (!Directory.Exists(str_ParentFolder)) { return(""); } } string extname; if (Fupload.PostedFile.FileName != "") { extname = Fupload.FileName.Substring(Fupload.FileName.LastIndexOf(".") + 1).ToUpper(); //判断上传课件类型 string str_UploadFileType = ConfigurationManager.AppSettings.Get("UploadFileType").ToLower(); if (str_UploadFileType.IndexOf(extname.ToLower()) == -1) { Response.Write("<script>alert('不允许上传 " + extname + " 类型的文件!');</script>"); return(""); } string str_sql; /*判断是否更名*/ if (tbx_Rename.Visible & tbx_Rename.Text.Trim() != "") { filename = tbx_Rename.Text.Trim() + "." + extname; } else { filename = Fupload.FileName; } if (File.Exists(str_ParentFolder + filename)) { Response.Write("<script>alert('文件 " + filename + " 已存在!');</script>"); return(""); } Fupload.PostedFile.SaveAs(str_ParentFolder + filename); Session["FilePath"] = str_ParentFolder + filename; str_sql = "Insert Into download (upfile ,shijian) Values ('" + filename + "','" + System.DateTime.Now.ToString() + "')"; DBFun.ExecuteUpdate(str_sql); Fupload.Dispose(); return(filename); } //用文件名上传的方式 //if (tbx_Research.Text != "") //{ // extname = System.IO.Path.GetExtension(tbx_Research.Text); // filename = dir + "\\" + DateTime.Now.ToString("yyyyMM") + rd.Next(1000).ToString() + extname; // System.IO.File.Copy(tbx_Research.Text, Server.MapPath(".\\kejian\\") + filename); // return filename; //} return(""); } catch { File.Delete(Session["FilePath"].ToString()); Response.Write("<script>alert('文件上传失败!');</script>"); return(""); } }