public string GetUpLoadFile(HtmlInputFile FilePicName, string FilePicPath, int FileSize) { if ((FileSize != 0) && (FilePicName.PostedFile.ContentLength > (FileSize * 0x400))) { HttpContext.Current.Response.Write("<script>alert('上传图片大小超出了限制');window.close();</script>"); HttpContext.Current.Response.End(); } switch (Path.GetFileName(FilePicName.PostedFile.FileName)) { case "": case null: HttpContext.Current.Response.Write("<script language=javascript>alert('请选择需要上传的文件!');window.close();</script>"); HttpContext.Current.Response.End(); break; } if (((((((FilePicName.PostedFile.ContentType != "image/gif") && (FilePicName.PostedFile.ContentType != "image/pjpeg")) && ((FilePicName.PostedFile.ContentType != "image/bmp") && (FilePicName.PostedFile.ContentType != "image/x-png"))) && (((FilePicName.PostedFile.ContentType != "image/jpeg") && (FilePicName.PostedFile.ContentType != "application/x-shockwave-flash")) && ((FilePicName.PostedFile.ContentType != "application/vnd.ms-excel") && (FilePicName.PostedFile.ContentType != "application/msword")))) && ((((FilePicName.PostedFile.ContentType != "application/vnd.ms-powerpoint") && (FilePicName.PostedFile.ContentType != "application/octet-stream")) && ((FilePicName.PostedFile.ContentType != "application/x-zip-compressed") && (FilePicName.PostedFile.ContentType != "pplication/vnd.rn-realmedia"))) && (((FilePicName.PostedFile.ContentType != "application/vnd.rn-realmedia-vbr") && (FilePicName.PostedFile.ContentType != "video/x-ms-wmv")) && ((FilePicName.PostedFile.ContentType != "audio/x-ms-wma") && (FilePicName.PostedFile.ContentType != "video/x-ms-asf"))))) && ((((FilePicName.PostedFile.ContentType != "video/avi") && (FilePicName.PostedFile.ContentType != "audio/mp3")) && ((FilePicName.PostedFile.ContentType != "video/mpeg4") && (FilePicName.PostedFile.ContentType != "video/mpg"))) && (((FilePicName.PostedFile.ContentType != "audio/mid") && (FilePicName.PostedFile.ContentType != "video/avi")) && (FilePicName.PostedFile.ContentType != "application/x-rar-compressed")))) && (FilePicName.PostedFile.ContentType != "application/x-zip-compressed")) { HttpContext.Current.Response.Write("<script>alert('上传文件格式不正确!');window.close();</script>"); HttpContext.Current.Response.End(); return ""; } string extension = Path.GetExtension(FilePicName.PostedFile.FileName); string fileName = Function.GetFileName(); string str4 = DateTime.Now.ToString("yyyyMM"); string path = HttpContext.Current.Server.MapPath(FilePicPath) + str4 + "/"; if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } string filename = path + fileName + extension; FilePicName.PostedFile.SaveAs(filename); return (str4 + "/" + fileName + extension); }
public string UploadFile(HtmlInputFile fUpload) { string fPath = String.Empty; try { fPath = Server.MapPath(ResolveUrl("~/") + "Upload/Files/" + fUpload.PostedFile.FileName); string[] splitdot = fPath.Split(new char[1] { '.' }); string dot = splitdot[splitdot.Length - 1].ToLower(); if (dot.ToLower() == "xls") { FileInfo fInfo = new FileInfo(fPath); if (fInfo.Exists) { fInfo.Delete(); } fUpload.PostedFile.SaveAs(fPath); Path = fPath; } else { //Tool.Message(this.Page, "Bạn phải chọn phải đuôi .xls"); } } catch (Exception ex) { throw new Exception(ex.ToString()); } return fPath; }
public string Up(System.Web.UI.HtmlControls.HtmlInputFile File2, string Pa) { // // TODO: 在此处添加构造函数逻辑 // if (File2.PostedFile.ContentLength.ToString() == "0") { return("0"); } else { //获取文件名称 string ss; fname = System.DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString(); ss = System.DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString() + Path.GetExtension(File2.PostedFile.FileName); if (File2.PostedFile.ContentLength / 1024 > 10000000) { return("1"); } else { string ty = File2.PostedFile.ContentType; File2.PostedFile.SaveAs(System.Web.HttpContext.Current.Server.MapPath(Pa) + ss); s = "uploadfiles/" + ss; return("3"); //Up= ss; } } }
public string uploadWord(System.Web.UI.HtmlControls.HtmlInputFile uploadFiles) { if (uploadFiles.PostedFile != null) { string fileName = uploadFiles.PostedFile.FileName; int extendNameIndex = fileName.LastIndexOf("."); string extendName = fileName.Substring(extendNameIndex); string newName = ""; try { //验证是否为word格式 if (extendName == ".doc") { DateTime now = DateTime.Now; newName = now.DayOfYear.ToString() + uploadFiles.PostedFile.ContentLength.ToString(); //上传路径 指当前上传页面的同一级的目录下面的wordTmp路径 uploadFiles.PostedFile.SaveAs(System.Web.HttpContext.Current.Server.MapPath("wordTmp/" + newName + extendName)); } else { return("1"); } } catch { return("0"); } //return "http://" + HttpContext.Current.Request.Url.Host + HttpContext.Current.Request.ApplicationPath + "/wordTmp/" + newName + extendName; return(System.Web.HttpContext.Current.Server.MapPath("wordTmp/" + newName + extendName)); } else { return("0"); } }
/// <summary> /// 单文件上传 /// </summary> /// <param name="file">文件上传控件</param> /// <param name="filetype">文件类型限制 例:new string[]{"image/gif","image/pjpeg"}</param> /// <param name="fileLength">文件大小限制[KB]</param> /// <param name="fullPath">文件要上传到的文件夹[全路径,不要带末尾的"\"] 例:Server.MapPath("../uploads")</param> /// <returns>上传后的文件名</returns> static public string Upload(System.Web.UI.HtmlControls.HtmlInputFile file, string[] filetype, int fileLength, string fullPath) { bool checkType = false; foreach (string str in filetype) { if (file.PostedFile.ContentType.ToString() == str) { checkType = true; break; } } if (!checkType) { return("错误:您上传的文件是不允许的类型"); } else { if (file.PostedFile.ContentLength > fileLength * 1024) { return("错误:文件超出大小限制!"); } else { Random rand = new Random(unchecked ((int)DateTime.Now.Ticks)); string extender = Path.GetExtension(file.PostedFile.FileName); string filename = DateTime.Now.ToShortDateString().Replace("-", "") + rand.Next().ToString().Substring(0, 5) + extender; file.PostedFile.SaveAs(fullPath + "\\" + filename); return(filename); } } }
/// <summary> /// 上传Word文档 /// </summary> /// <param name="inputFile"></param> /// <param name="filePath"></param> private string UpLoadFile(HtmlInputFile inputFile) { string fileName, fileExtension; //建立上传对象 HttpPostedFile postedFile = inputFile.PostedFile; fileName = System.IO.Path.GetFileName(postedFile.FileName); fileExtension = System.IO.Path.GetExtension(fileName); //上传图片保存Base路径 如果修改此路径需要同时修改图片地址替换路径(在212行附件) string phyPath = Server.MapPath("~/") + "FckUpload\\ImportWord\\0\\"; //判断路径是否存在,若不存在则创建路径 DirectoryInfo upDir = new DirectoryInfo(phyPath); if (!upDir.Exists) { upDir.Create(); } //保存文件 try { postedFile.SaveAs(phyPath + fileName); } catch { } return phyPath + fileName; }
public string adjuntarArchivo(System.Web.UI.HtmlControls.HtmlInputFile fuControl, string uploadPath, string fileName) { if (fuControl.PostedFile != null) { // Indicamos la ruta string path = HttpContext.Current.ApplicationInstance.Server.MapPath(uploadPath); // Armamos el nombre del archivo string fn = System.IO.Path.GetFileName(fileName + ".pdf"); // Obtenemos los parametros del archivo por subir var fileSize = fuControl.PostedFile.ContentLength; var fileMimeType = fuControl.PostedFile.ContentType; //lblStatus.Text = "Size: " + fileSize + ", MIME: " + fileMimeType; if (Path.GetExtension(fuControl.PostedFile.FileName).ToLower() != ".pdf") { return("El archivo debe ser tipo PDF"); } if (fileSize > 2048000) { return("El archivo debe ser menor a 2MB"); } // Subimos el archivo fuControl.PostedFile.SaveAs(System.IO.Path.Combine(path, fn)); } return("ok"); }
/// <summary> /// 上传文件 /// </summary> /// <param name="file">要上传文件的控件</param> /// <param name="strFolder">要上传的目录</param> /// <returns>返回文件名称</returns> public string UploadFile(System.Web.UI.HtmlControls.HtmlInputFile file, string strFolder) { if (file.PostedFile.ContentLength != 0) { string strFileName = file.Value; strFileName = strFileName.Substring(strFileName.LastIndexOf(@"\") + 1, strFileName.Length - strFileName.LastIndexOf(@"\") - 1); if (strFileName.LastIndexOf(".") != -1) { strFileName = strFileName.Substring(strFileName.LastIndexOf(@"."), strFileName.Length - strFileName.LastIndexOf(@".")); strFileName = GetRand(10000000, 99999999) + strFileName; while (System.IO.File.Exists(this.Request.PhysicalApplicationPath + strFolder + strFileName)) { strFileName = GetRand(10000000, 99999999) + strFileName; } } else { strFileName = GetRand(10000000, 99999999); while (System.IO.File.Exists(this.Request.PhysicalApplicationPath + strFolder + strFileName)) { strFileName = GetRand(10000000, 99999999); } } file.PostedFile.SaveAs(this.Request.PhysicalApplicationPath + strFolder + strFileName); return(strFileName); } else { return(""); } }
public string SaveFileOnServer(System.Web.UI.HtmlControls.HtmlInputFile fileImport) { ErrHandler.MyErrHandler.WriteError("SincronizareDateAngajati.ascx - start - SaveFileOnServer() - " + fileImportFisier.PostedFile.FileName); string fn = System.IO.Path.GetFileName(fileImport.PostedFile.FileName); string numeFis = fn.Substring(0, fn.LastIndexOf(".")); string extensie = fn.Substring(fn.LastIndexOf(".")); string SaveLocation = Server.MapPath("Templates\\Bulk") + "\\" + numeFis + "_" + DateTime.Now.Year + DateTime.Now.Month + DateTime.Now.Day + "_" + DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second + extensie; try { fileImport.PostedFile.SaveAs(SaveLocation); //Response.Write("The file has been uploaded."); } catch (Exception ex) { //Response.Write("Error: " + ex.Message); //Note: Exception.Message returns a detailed message that describes the current exception. //For security reasons, we do not recommend that you return Exception.Message to end users in //production environments. It would be better to put a generic error message. ErrHandler.MyErrHandler.WriteError("SincronizareDateAngajati.ascx - error - SaveFileOnServer() - " + ex.Message); } ErrHandler.MyErrHandler.WriteError("SincronizareDateAngajati.ascx - end - SaveFileOnServer() - " + SaveLocation); return(SaveLocation); }
//private string findPulsColor(string idAmm) //{ // return FileManager.findPulsColor(idAmm); //} private bool verificaFile(System.Web.UI.HtmlControls.HtmlInputFile upload) { if (upload.Value == "" || upload.Value == null) { ClientScript.RegisterStartupScript(this.GetType(), "selezioneNonValida_1", "alert('Selezionare un file valido.');", true); return(false); } //Controllo del tipo di file if (upload.Value != "") { if (upload.Value != null) { string[] path = upload.Value.Split('.'); if (path.Length != 0) { if (path[path.Length - 1].ToLower() != "gif" && path[path.Length - 1].ToLower() != "jpg") { ClientScript.RegisterStartupScript(this.GetType(), "selezioneNonValida_2", "alert('I files validi sono solo quelli con estensione .gif o .jpg');", true); return(false); } } } } return(true); }
public static string SaveSmallImage(HtmlInputFile File1, string SaveFileFolder) { string str = string.Empty; if (File1.Value != "") { string extension = Path.GetExtension(File1.Value); string str3 = Guid.NewGuid().ToString("n"); string str4 = str3 + extension; string str5 = str3 + "_s" + extension; string path = HttpContext.Current.Server.MapPath(SaveFileFolder) + str4; string str7 = HttpContext.Current.Server.MapPath(SaveFileFolder) + str5; string str8 = SaveFileFolder + str5; if (File.Exists(path)) { Public.Show("已存在相同文件名,请重新上传JPG图片!"); return str; } ReadXML dxml = new ReadXML(); string str9 = HttpContext.Current.Server.MapPath(SaveFileFolder); if (!Directory.Exists(str9)) { Directory.CreateDirectory(str9); } File1.PostedFile.SaveAs(path); CreatSmallPic(path, str7, dxml.smallPicWidth, dxml.smallPicHeight); str = str8; if (File.Exists(path)) { File.Delete(path); } } return str; }
/// </summary> /// <param name="page"></param> /// <param name="fil"></param> /// <param name="strLujing"></param> /// <returns></returns> public static string meUpfile(System.Web.UI.HtmlControls.HtmlInputFile fil, string strLujing, bool isFile) { //返回 "" 失败 //正常 返回 需要存入数据库的路径 System.Web.UI.Page page; page = HttpContext.Current.Handler as System.Web.UI.Page; if (fil.PostedFile.FileName.Trim() != "") { try { string filename; string strReturn; string nam1; nam1 = fil.PostedFile.FileName; string newext1; newext1 = nam1.Substring(nam1.LastIndexOf(".")).ToLower(); // if (newext1!=".jpg" && newext1!=".jpeg" && newext1!=".gif") // return ""; DateTime now1; now1 = DateTime.Now; string newname1; //if (fil.PostedFile.ContentLength > 100000000) // strReturn = "0"; //else //{ if (isFile) { string filePath = page.Server.MapPath(strLujing + fil.PostedFile.FileName); if (File.Exists(filePath)) { File.Delete(filePath); } fil.PostedFile.SaveAs(page.Server.MapPath(strLujing + fil.PostedFile.FileName)); strReturn = strLujing.Replace("///", "/") + fil.PostedFile.FileName; } else { newname1 = now1.DayOfYear.ToString() + fil.PostedFile.ContentLength.ToString() + System.DateTime.Now.Millisecond.ToString(); filename = newname1 + newext1; fil.PostedFile.SaveAs(page.Server.MapPath(strLujing + filename)); strReturn = strLujing.Replace("///", "/") + filename; } //} return(strReturn); } catch (Exception ex) { throw new Exception(ex.Message); } } else { return(""); } }
private void AddAttachControl() { string Template; UDS.Components.DocumentFlow df = new UDS.Components.DocumentFlow(); Template = df.GetStyleTemplate(FlowID); if (Template != "") { TableRow tr = new TableRow(); TableCell td = new TableCell(); TableCell tl = new TableCell(); td.Text = "<a href='" + Template + "' style='text-decoration: underline' titile='模板下载' target='_blank'>模板</a>:"; td.HorizontalAlign = HorizontalAlign.Right; tr.Cells.Add(td); System.Web.UI.HtmlControls.HtmlInputFile hif = new System.Web.UI.HtmlControls.HtmlInputFile(); hif.ID = "fileTemplate"; hif.Name = "fileTemplate"; hif.Style["width"] = "450px"; hif.Style["Class"] = "Input3"; tl.Controls.Add(hif); tr.Cells.Add(tl); ht.Rows.Add(tr); td = null; tr = null; } df = null; }
private void CheckValidFile(HtmlInputFile file) { if(file.PostedFile==null || file.PostedFile.FileName.Trim().Length==0 || file.PostedFile.ContentLength==0) return; string filename = file.PostedFile.FileName; int pos = filename.LastIndexOfAny(new char[]{'/','\\'}); if(pos>=0) filename = filename.Substring(pos+1); pos = filename.LastIndexOf('.'); if(pos>=0) { switch(filename.Substring(pos+1).ToLower()) { default: break; case "asp": case "aspx": case "ascx": case "config": case "php": case "php3": case "js": case "vb": case "vbs": throw new Exception(String.Format(GetText("fileerror"),filename)); } } }
public string Up(System.Web.UI.HtmlControls.HtmlInputFile File2, string Pa) { // // TODO: 在此处添加构造函数逻辑 // if (File2.PostedFile.ContentLength.ToString() == "0") { return("0"); } else { //获取文件名称 string ss; ss = System.DateTime.Now.ToString().Replace("-", "").Replace(" ", "").Replace(":", "") + Path.GetExtension(File2.PostedFile.FileName); if (File2.PostedFile.ContentLength / 1024 > 100000) { return("1"); } else { string ty = File2.PostedFile.ContentType; File2.PostedFile.SaveAs(System.Web.HttpContext.Current.Server.MapPath(Pa) + ss); s = ss; return("3"); //Up= ss; } } }
protected override void CreateChildControls() { Controls.Clear(); inputFile = new HtmlInputFile {ID = "inputFile"}; inputFile.Attributes["onchange"] = OnSelected; Controls.Add(inputFile); }
public static void Flip(HtmlInputFile file, System.Web.UI.WebControls.Image img, bool blnReadOnly) { img.Visible = blnReadOnly; file.Visible = !blnReadOnly; if (blnReadOnly && (file.PostedFile.ContentLength != 0)) { img.ImageUrl = file.PostedFile.FileName; } }
public string getBase64StringFromInputFile(string path,HtmlInputFile file) { using (file) { Image img = Image.FromFile(path + file.PostedFile.FileName); byte[] imageBytes = imageToByteArray(img); string base64String = Convert.ToBase64String(imageBytes, 0, imageBytes.Length); return "data:image/png;base64," + base64String; } }
/// <summary> /// 上传Excel文件 /// </summary> /// <param name="inputfile">上传的控件名</param> /// <returns></returns> private string UpLoadXls(System.Web.UI.HtmlControls.HtmlInputFile inputfile) { string orifilename = string.Empty; string uploadfilepath = string.Empty; string modifyfilename = string.Empty; string fileExtend = ""; //文件扩展名 int fileSize = 0; //文件大小 try { if (inputfile.Value != string.Empty) { //得到文件的大小 fileSize = inputfile.PostedFile.ContentLength; if (fileSize == 0) { throw new Exception("导入的Excel文件大小为0,请检查是否正确!"); } //得到扩展名 fileExtend = inputfile.Value.Substring(inputfile.Value.LastIndexOf(".") + 1); if (fileExtend.ToLower() != "xls" && fileExtend.ToLower() != "xlsx") { throw new Exception("你选择的文件格式不正确,只能导入EXCEL文件!"); } //路径 uploadfilepath = Server.MapPath("~/Service/GraduateChannel/GraduateApply/ImgUpLoads"); //新文件名 modifyfilename = System.Guid.NewGuid().ToString(); modifyfilename += "." + inputfile.Value.Substring(inputfile.Value.LastIndexOf(".") + 1); //判断是否有该目录 System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(uploadfilepath); if (!dir.Exists) { dir.Create(); } orifilename = uploadfilepath + "\\" + modifyfilename; //如果存在,删除文件 if (File.Exists(orifilename)) { File.Delete(orifilename); } // 上传文件 inputfile.PostedFile.SaveAs(orifilename); } else { throw new Exception("请选择要导入的Excel文件!"); } } catch (Exception ex) { throw ex; } return(orifilename); }
public string LetterWaterMark(HtmlInputFile FilePicName, string FilePicPath, string UpLoadPicPath) { Font font; B_SiteInfo info = new B_SiteInfo(); M_Site siteModel = new M_Site(); siteModel = info.GetSiteModel(); string str = ""; if (UpLoadPicPath == "") { str = this.NotWaterMark_NotNewSize(FilePicName, FilePicPath); } else { str = UpLoadPicPath; } string waterMarkStr = siteModel.WaterMarkStr; int waterMarkFontSize = siteModel.WaterMarkFontSize; string waterMarkFontName = siteModel.WaterMarkFontName; string waterMarkFontColor = siteModel.WaterMarkFontColor; bool waterMarkIsBold = siteModel.WaterMarkIsBold; string path = HttpContext.Current.Server.MapPath(FilePicPath) + str; string[] strArray = str.Split(new char[] { '/' }); string[] strArray2 = strArray[1].Split(new char[] { '.' }); string destFileName = HttpContext.Current.Server.MapPath(FilePicPath) + strArray[0] + strArray2[0] + "_1" + strArray2[1]; if (File.Exists(path)) { File.Copy(path, destFileName); } Image image = Image.FromFile(destFileName); Graphics graphics = Graphics.FromImage(image); graphics.CompositingQuality = CompositingQuality.HighQuality; graphics.SmoothingMode = SmoothingMode.HighQuality; graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; graphics.DrawImage(image, 0, 0, image.Width, image.Height); if (waterMarkIsBold) { font = new Font(waterMarkFontName, (float) waterMarkFontSize, FontStyle.Bold); } else { font = new Font(waterMarkFontName, (float) waterMarkFontSize); } Brush brush = new SolidBrush(ColorTranslator.FromHtml("#" + waterMarkFontColor)); string s = waterMarkStr; graphics.DrawString(s, font, brush, (float) 0f, (float) 0f); graphics.Dispose(); image.Save(path); image.Dispose(); if (File.Exists(destFileName)) { File.Delete(destFileName); } return str; }
public static bool IsAllowedLength(HtmlInputFile hifile) { //�����ϴ��ļ���С�����ֵ,���Ա�����xml�ļ���,��λΪKB int i = 512; //����ϴ��ļ��Ĵ�С�������ֵ,����flase,����true. if (hifile.PostedFile.ContentLength > i * 512) { return false; } return true; }
/// <summary> /// 验证上传文件,不能为0字节。 /// </summary> /// <param name="fileInput">The file input.</param> public static void Validate(this HtmlInputFile fileInput) { if (string.IsNullOrEmpty(fileInput.PostedFile.FileName)) { throw new Exception("没有文件被上传。"); } if (fileInput.PostedFile.ContentLength == 0) { throw new Exception("文件长度必须大于0。"); } }
/// <summary> /// 上载文件 /// </summary> private string UploadAtt() { HtmlForm FrmCompose = (HtmlForm)this.Page.FindControl("Display"); UDS.Components.BBSClass bbs = new UDS.Components.BBSClass(); string FileName = ""; string Extension = ""; string SavedName = ""; string TotalSavedName = ""; try { if (System.IO.Directory.Exists(Server.MapPath(".") + "\\Attachment")) { for (int i = 0; i < FrmCompose.Controls.Count; i++) { if (FrmCompose.Controls [i].GetType().ToString() == "System.Web.UI.HtmlControls.HtmlInputFile") { HtmlInputFile hif = ((HtmlInputFile)(FrmCompose.Controls[i])); if (hif.PostedFile.FileName.Trim() != "") { FileName = System.IO.Path.GetFileName(hif.PostedFile.FileName); Extension = System.IO.Path.GetExtension(hif.PostedFile.FileName); SavedName = bbs.InsertFile(FileName, Extension).ToString(); TotalSavedName += SavedName + Extension + ","; hif.PostedFile.SaveAs(Server.MapPath(".") + "\\Attachment\\" + SavedName + Extension); } hif = null; } } return(TotalSavedName); } else { System.IO.Directory.CreateDirectory(Server.MapPath(".") + "\\Attachment"); UploadAtt(); return(TotalSavedName); } } catch (Exception ioex) { UDS.Components.Error.Log(ioex.ToString()); Server.Transfer("../../../Error.aspx"); return(TotalSavedName); } }
public static void CoverFile(HtmlInputFile ffFile,string strAbsolutePath,string strOldFileName) { //������ļ��� string strNewFileName = GetUniqueString(); if(ffFile.PostedFile.FileName != string.Empty) { //��ͼƬ��Ϊ��ʱ��ɾ����ͼƬ if(strOldFileName != string.Empty) { DeleteFile(strAbsolutePath,strOldFileName); } SaveFile(ffFile,strAbsolutePath); } }
private System.Drawing.Image ConvertToImage(HtmlInputFile file) { if (file.PostedFile.ContentLength > 0) { try { using (System.Drawing.Image input = System.Drawing.Image.FromStream(file.PostedFile.InputStream)) { file.PostedFile.SaveAs(WebHelper.GetImageWorkingDirectory() + "web\\Large\\" + file.PostedFile.FileName); return input; } } catch { } } return null; }
/// <summary> /// Uploads the user icon. /// </summary> /// <param name="fileInput">The file input.</param> /// <param name="virDir">The vir dir.</param> /// <param name="userid">The userid.</param> /// <param name="scaleLength">Length of the scale.</param> /// <param name="sMode">The s mode.</param> public static void UploadUserIcon(this HtmlInputFile fileInput, string virDir, object userid, int scaleLength, System.Drawing.ScaleModes sMode) { string dir = System.Web.HttpContext.Current.Server.MapPath(virDir); if (!System.IO.Directory.Exists(dir)) { System.IO.Directory.CreateDirectory(dir); } string fileName = userid.ToString() + ".jpg"; string fileSavePath = System.IO.Path.Combine(dir, fileName); System.Drawing.Image img = fileInput.ToImage(); img.Scale(fileSavePath, scaleLength, sMode); }
public bool TestExistFileUpload(HtmlInputFile file) { bool test = false; try { if (file.PostedFile.ContentLength != 0) { test = true; } } catch (Exception ex) { Console.Write(ex.ToString()); } return test; }
private void AddAttachControl() { string Template; long FlowID; UDS.Components.DocumentFlow df = new UDS.Components.DocumentFlow(); FlowID = df.GetDocumentFlowID(DocID); Template = df.GetStyleTemplate(FlowID); if (Template != "") { TableRow tr = new TableRow(); TableCell td = new TableCell(); TableCell tc = new TableCell(); Literal lt = new Literal(); lt.Text = "<a href='" + Template + "' style='text-decoration: underline' titile='模板下载' target='_blank'>模板</a>:"; tc.HorizontalAlign = HorizontalAlign.Right; tc.Width = Unit.Percentage(20); tc.Controls.Add(lt); td.HorizontalAlign = HorizontalAlign.Left; td.ColumnSpan = 5; System.Web.UI.HtmlControls.HtmlInputFile hif = new System.Web.UI.HtmlControls.HtmlInputFile(); hif.ID = "fileTemplate"; hif.Name = "fileTemplate"; hif.Style["width"] = Unit.Percentage(70).ToString(); hif.Style["Class"] = "Input3"; td.Controls.Add(hif); tr.Cells.Add(tc); tr.Cells.Add(td); tabDispDocument.Rows.Add(tr); td = null; tr = null; } df = null; }
/// <summary> /// 上传文件 /// </summary> /// <param name="filePath">保存文件地址</param> /// <param name="maxSize">文件最大大小</param> /// <param name="fileType">文件后缀类型</param> /// <param name="TargetFile">控件名</param> /// <param name="saveFileName">保存后的文件名和地址</param> /// <param name="fileSize">文件大小</param> /// <returns></returns> public string UploadFile(string filePath, int maxSize, string[] fileType, System.Web.UI.HtmlControls.HtmlInputFile TargetFile, out string saveFileName, out int fileSize) { saveFileName = ""; fileSize = 0; string Result = ""; //bool typeFlag = false; string FilePath = filePath; int MaxSize = maxSize; string strFileName, strNewName, strFilePath; if (TargetFile.PostedFile.FileName == "") { return("请选择上传的文件"); } strFileName = TargetFile.PostedFile.FileName; TargetFile.Accept = "*/*"; strFilePath = FilePath; if (Directory.Exists(strFilePath) == false) { Directory.CreateDirectory(strFilePath); } FileInfo myInfo = new FileInfo(strFileName); string strOldName = myInfo.Name; strNewName = strOldName.Substring(strOldName.LastIndexOf(".")); strNewName = strNewName.ToLower(); if (TargetFile.PostedFile.ContentLength <= MaxSize) { string strFileNameTemp = GetUploadFileName(); string strFilePathTemp = strFilePath; strOldName = strFileNameTemp + strNewName; strFilePath = strFilePath + "\\" + strOldName; fileSize = TargetFile.PostedFile.ContentLength / 1024; saveFileName = strFilePath.Substring(strFilePath.IndexOf("FileUpload\\")); TargetFile.PostedFile.SaveAs(strFilePath); TargetFile.Dispose(); } else { return("上传文件超出指定的大小"); } return(Result); }
public string wordToHtml(System.Web.UI.HtmlControls.HtmlInputFile wordFilePath) { Microsoft.Office.Interop.Word.ApplicationClass word = new Microsoft.Office.Interop.Word.ApplicationClass(); Type wordType = word.GetType(); Microsoft.Office.Interop.Word.Documents docs = word.Documents; // 打开文件 Type docsType = docs.GetType(); //应当先把文件上传至服务器然后再解析文件为html string filePath = uploadWord(wordFilePath); //判断是否上传文件成功 if (filePath == "0") { return("0"); } //判断是否为word文件 if (filePath == "1") { return("1"); } object fileName = filePath; Microsoft.Office.Interop.Word.Document doc = (Microsoft.Office.Interop.Word.Document)docsType.InvokeMember("Open", System.Reflection.BindingFlags.InvokeMethod, null, docs, new Object[] { fileName, true, true }); // 转换格式,另存为html Type docType = doc.GetType(); string filename = System.DateTime.Now.Year.ToString() + System.DateTime.Now.Month.ToString() + System.DateTime.Now.Day.ToString() + System.DateTime.Now.Hour.ToString() + System.DateTime.Now.Minute.ToString() + System.DateTime.Now.Second.ToString(); //被转换的html文档保存的位置 string ConfigPath = HttpContext.Current.Server.MapPath("~/keyfile/a.html"); object saveFileName = ConfigPath; docType.InvokeMember("SaveAs", System.Reflection.BindingFlags.InvokeMethod, null, doc, new object[] { saveFileName, Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatHTML }); //关闭文档 docType.InvokeMember("Close", System.Reflection.BindingFlags.InvokeMethod, null, doc, new object[] { null, null, null }); // 退出 Word wordType.InvokeMember("Quit", System.Reflection.BindingFlags.InvokeMethod, null, word, null); //转到新生成的页面 return("/" + filename + ".html"); }
public string GetUpLoadPicPath(HtmlInputFile FilePicName, string FilePicPath, bool WaterMark, bool NewSize, int MaxWidth, int MaxHeight, bool BiLi, int BiLiValue, int FileSize) { string fileName = Path.GetFileName(FilePicName.PostedFile.FileName); string str2 = Path.GetExtension(FilePicName.PostedFile.FileName).ToString(); bool flag = false; if ((FileSize != 0) && (FilePicName.PostedFile.ContentLength > (FileSize * 0x400))) { HttpContext.Current.Response.Write("<script>alert('上传图片大小超出了限制');window.close();</script>"); HttpContext.Current.Response.End(); } B_SiteInfo info = new B_SiteInfo(); string imgUploadType = info.GetInfoModel().ImgUploadType; string[] strArray = imgUploadType.Split(new char[] { '|' }); for (int i = 0; i < strArray.Length; i++) { if (strArray[i].ToLower() == str2.ToLower()) { flag = true; break; } } if (!flag) { HttpContext.Current.Response.Write("<script>alert('上传图片格式只能够是:" + imgUploadType + "!');window.close();</script>"); HttpContext.Current.Response.End(); } M_Site siteModel = new M_Site(); siteModel = info.GetSiteModel(); if (NewSize) { return this.PicNewSize(FilePicName, FilePicPath, WaterMark, MaxWidth, MaxHeight, BiLi, BiLiValue); } if (WaterMark) { if (siteModel.IsImgWaterMark) { return this.PicWaterMark(FilePicName, FilePicPath, ""); } return this.LetterWaterMark(FilePicName, FilePicPath, ""); } return this.NotWaterMark_NotNewSize(FilePicName, FilePicPath); }
/**//// <summary> /// 构造函数 /// </summary> private FileHelper() { } #region 上传文件 /**//// <summary> /// 上传文件 /// </summary> /// <param name="inputFile">html上传控件</param> /// <param name="uploadDirectory">上传到服务器目录</param> /// <param name="limitSite">上传文件大小限制(单位:字节)</param> /// <param name="fileName">输出文件名</param> /// <returns>返回操作逻辑值</returns> public static bool UpFile(HtmlInputFile inputFile, string uploadDirectory, int limitSite,out string fileName) { string acc = inputFile.PostedFile.FileName;//文件及路径名 string accessory = string.Empty; //记录文件名 fileName = string.Empty; //输出文件名 if(inputFile.PostedFile.ContentLength > limitSite) { System.Web.HttpContext.Current.Response.Write("<script language=javascript>alert('上传文件限制最大为"+Convert.ToString(limitSite/1024)+"k');history.back(-1);</script>"); System.Web.HttpContext.Current.Response.End(); return false; } else { if(acc.Trim().Length > 0) { //将新文件名以GUID重命名 accessory = System.Guid.NewGuid().ToString() +"."+ GetFileType(acc); if(!System.IO.Directory.Exists(uploadDirectory)) { System.IO.Directory.CreateDirectory(uploadDirectory); } string access= uploadDirectory + accessory; try { inputFile.PostedFile.SaveAs(access); fileName = accessory; return true; } catch (Exception) { return false; } } } return false; }
public string UploadPicFile(System.Web.UI.HtmlControls.HtmlInputFile Fupload) { //文件上传 if (Fupload.PostedFile.FileName == "" && TbPicUrl.Text == "") { return(""); } string dir = DateTime.Now.ToString("yyyyMM"); if (!Directory.Exists(Server.MapPath("..\\Film_Poster\\") + dir)) { Directory.CreateDirectory(Server.MapPath("..\\Film_Poster\\") + dir); if (!Directory.Exists(Server.MapPath("..\\Film_Poster\\") + dir)) { return(""); } } Random rd = new System.Random(); string filename; string extname; if (Fupload.PostedFile.FileName != "") { extname = Fupload.PostedFile.FileName.Substring(Fupload.PostedFile.FileName.LastIndexOf(".") + 1).ToUpper(); if ("JPG|GIF|BMP|PNG".IndexOf(extname) == -1) { return(""); } filename = dir + "\\" + DateTime.Now.ToString("yyyyMM") + rd.Next(1000).ToString() + "." + extname; Fupload.PostedFile.SaveAs(Server.MapPath("..\\Film_Poster\\") + filename); return(filename); } if (TbPicUrl.Text != "") { return(TbPicUrl.Text); } return(""); }
public string uploadWord(System.Web.UI.HtmlControls.HtmlInputFile uploadFiles) { string fileName = uploadFiles.PostedFile.FileName; int extendNameIndex = fileName.LastIndexOf("."); string extendName = fileName.Substring(extendNameIndex); string newName = ""; try { DateTime now = DateTime.Now; newName = now.DayOfYear.ToString() + uploadFiles.PostedFile.ContentLength.ToString(); //Response.Write(System.Web.HttpContext.Current.Server.MapPath("~/wpic/" + newName + extendName)); //上传路径 指当前上传页面的同一级的目录下面的wordTmp路径 uploadFiles.PostedFile.SaveAs(System.Web.HttpContext.Current.Server.MapPath("~/upload/" + newName + extendName)); } catch { return("0"); } return(System.Web.HttpContext.Current.Server.MapPath("~/upload/" + newName + extendName)); }
public string Up1(System.Web.UI.HtmlControls.HtmlInputFile File2, string Pa, string name) { // // TODO: 在此处添加构造函数逻辑 // if (File2.PostedFile.ContentLength.ToString() == "0") { return("0"); } else { //获取文件名称 string ss; ss = name + Path.GetExtension(File2.PostedFile.FileName); string ss1 = Path.GetExtension(File2.PostedFile.FileName); if (File2.PostedFile.ContentLength / 1024 > 10000) { return("1"); } else { string ty = ss1; if (ty == ".doc") { File2.PostedFile.SaveAs(System.Web.HttpContext.Current.Server.MapPath(Pa) + ss); s1 = "../Uploads/studentWork/" + ss; return("3"); //Up= ss; } else { return("2"); } } } }
private bool insertFile(System.Web.UI.HtmlControls.HtmlInputFile upload, string typeFile, string name) { HttpPostedFile p = upload.PostedFile; Stream fs = p.InputStream; byte[] dati = new byte[fs.Length]; fs.Read(dati, 0, (int)fs.Length); fs.Close(); bool result = true; int num = p.FileName.LastIndexOf('\\'); string fileInput = p.FileName.Substring(num + 1); string[] estensione = fileInput.Split('.'); SAAdminTool.DocsPaWR.DocsPaWebService ws = new SAAdminTool.DocsPaWR.DocsPaWebService(); string[] amministrazione = ((string)Session["AMMDATASET"]).Split('@'); string idAmm = amministrazione[3]; string nomeFile = name + idAmm + "." + estensione[1]; ws.Timeout = System.Threading.Timeout.Infinite; SAAdminTool.AdminTool.Manager.SessionManager sessionManager = new SAAdminTool.AdminTool.Manager.SessionManager(); try { result = insert(sessionManager.getUserAmmSession(), dati, nomeFile, ws.getpath(typeFile)); utils.InitImagePath.getInstance(idAmm).clear(); return(result); } catch (Exception e) { //Debugger.Write("Errore in DocsPaWS.asmx - metodo: insertFile", e); return(false); } return(result); }
public static bool IsAllowedExtension(HtmlInputFile hifile) { string strOldFilePath = "",strExtension = ""; //�����ϴ�����չ�������Ըijɴ������ļ��ж��� string[] arrExtension = { ".gif", ".GIF", ".JPG", ".jpg", ".JPEG", ".BMP", ".PNG", ".jpeg", ".bmp", ".png" }; if(hifile.PostedFile.FileName != string.Empty) { strOldFilePath = hifile.PostedFile.FileName; //ȡ���ϴ��ļ�����չ�� strExtension = strOldFilePath.Substring(strOldFilePath.LastIndexOf(".")); //�жϸ���չ���Ƿ�Ϸ� for(int i = 0; i< arrExtension.Length; i++) { if(strExtension.Equals(arrExtension[i])) { return true; } } } return false; }
public string word2Html(System.Web.UI.HtmlControls.HtmlInputFile wordFilePath) { string filePath = uploadWord(wordFilePath); Stream f = new FileStream(filePath, FileMode.Open); Document doc = new Document(f); string filename = System.DateTime.Now.Year.ToString() + System.DateTime.Now.Month.ToString() + System.DateTime.Now.Day.ToString() + System.DateTime.Now.Hour.ToString() + System.DateTime.Now.Minute.ToString() + System.DateTime.Now.Second.ToString(); //被转换的html文档保存的位置 string ConfigPath = HttpContext.Current.Server.MapPath("~/upload/" + filename + ".htm"); doc.Save(ConfigPath, SaveFormat.Html); Thread.Sleep(3000); // f.Dispose(); this.GetHtmText(ConfigPath); File.Delete(filePath); File.Delete(ConfigPath); return("/html"); }
public string UpLoadSoft(HtmlInputFile FilePicName, string FilePicPath) { string fileName = Path.GetFileName(FilePicName.PostedFile.FileName); string str2 = Path.GetExtension(FilePicName.PostedFile.FileName).ToString(); bool flag = false; B_SiteInfo info = new B_SiteInfo(); string softUploadType = info.GetInfoModel().SoftUploadType; string[] strArray = softUploadType.Split(new char[] { '|' }); for (int i = 0; i < strArray.Length; i++) { if (strArray[i].ToLower() == str2.ToLower()) { flag = true; break; } } if (!flag) { HttpContext.Current.Response.Write("<script>alert('上传软件格式只能够是:" + softUploadType + "');window.history.go(-1);</script>"); HttpContext.Current.Response.End(); } if ((((FilePicName.PostedFile.ContentType == "text/asp") || (FilePicName.PostedFile.ContentType == "video/x-ms-asf")) || ((FilePicName.PostedFile.ContentType == "text/html") || (FilePicName.PostedFile.ContentType == "application/xml"))) || (FilePicName.PostedFile.ContentType == "text/plain")) { HttpContext.Current.Response.Write("<script>alert('上传文件格式不正确,请压缩后再上传');window.history.go(-1);</script>"); HttpContext.Current.Response.End(); } string str4 = Function.GetFileName(); string str5 = DateTime.Now.ToString("yyyyMM"); string path = HttpContext.Current.Server.MapPath(FilePicPath) + str5 + "/"; if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } string filename = path + str4 + str2; FilePicName.PostedFile.SaveAs(filename); return ("/" + str5 + "/" + str4 + str2); }
private void AddAttachControl() { string Template; UDS.Components.DocumentFlow df = new UDS.Components.DocumentFlow(); Template = df.GetStyleTemplateEx(StyleID); if(Template!="") { TableRow tr = new TableRow(); TableCell td = new TableCell(); TableCell tl = new TableCell(); TableCell tt = new TableCell(); tt.Text =" "; tr.Cells.Add(tt); td.Text = "<a href='" + Template + "' style='text-decoration: underline' titile='ģ������'>ģ��</a>:"; td.HorizontalAlign = HorizontalAlign.Right; tr.Cells.Add(td); System.Web.UI.HtmlControls.HtmlInputFile hif = new System.Web.UI.HtmlControls.HtmlInputFile(); hif.ID = "fileTemplate"; hif.Name = "fileTemplate"; hif.Style["width"] = "450px"; hif.Style["Class"] = "Input3"; tl.Controls.Add(hif); tr.Cells.Add(tl); tabDemo.Rows.Add(tr); td = null; tr = null; } df = null; }
private void CreateUploadCell(TableRow row, int index) { using (TableCell cell = new TableCell()) { using (HtmlInputFile file = new HtmlInputFile()) { file.ID = "FileUpload" + index; file.Attributes.Add("class", "hidden upload"); file.Name = "file"; cell.Controls.Add(file); } using (HtmlInputButton browseButton = new HtmlInputButton()) { browseButton.ID = "BrowseButton" + index; browseButton.Attributes.Add("class", "browse ui small blue button"); browseButton.Value = Titles.Browse; cell.Controls.Add(browseButton); } row.Controls.Add(cell); } }
//允许以程序设计方式存取服务器上的HTML项目 public string Up(System.Web.UI.HtmlControls.HtmlInputFile File2, string Pa) { // // TODO: 在此处添加构造函数逻辑 // if (File2.PostedFile.ContentLength.ToString() == "0") { return("0"); } else { //设置文件名称 获取指定路径字符串的扩展名 string ss; ss = System.DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString() + Path.GetExtension(File2.PostedFile.FileName); string ty = File2.PostedFile.ContentType; //指定存储路径 File2.PostedFile.SaveAs(System.Web.HttpContext.Current.Server.MapPath(Pa) + ss); s = ss; return("3"); //Up= ss; } }
public static int UploadFile(Page page, HtmlInputFile file, string TargetDirectory, ref string NewFileName, string LimitFileTypeList) { if (!m000001(file, LimitFileTypeList)) { return -101; } if (file.Value.Trim() == "") { return -1; } if (!TargetDirectory.EndsWith("/") && !TargetDirectory.EndsWith(@"\")) { TargetDirectory = TargetDirectory + "/"; } string extension = Path.GetExtension(file.Value); NewFileName = GetNewFileName(page, TargetDirectory, extension, ""); try { file.PostedFile.SaveAs(page.Server.MapPath(TargetDirectory + NewFileName)); } catch { return -3; } return 0; }
/// <summary> /// �����ļ� /// </summary> private string UploadAtt() { HtmlForm FrmCompose = (HtmlForm)this.Page.FindControl("NewItem"); UDS.Components.BBSClass bbs = new UDS.Components.BBSClass(); string FileName = ""; string Extension = ""; string SavedName = ""; string TotalSavedName = ""; try { if(System.IO.Directory.Exists(Server.MapPath(".")+"\\Attachment")) { for (int i=0;i<FrmCompose.Controls.Count;i++) { if(FrmCompose.Controls [i].GetType().ToString()=="System.Web.UI.HtmlControls.HtmlInputFile") { HtmlInputFile hif = ((HtmlInputFile)(FrmCompose.Controls[i])); if(hif.PostedFile.FileName.Trim()!="") { FileName = System.IO .Path.GetFileName(hif.PostedFile.FileName); Extension = System.IO.Path.GetExtension(hif.PostedFile.FileName); SavedName = bbs.InsertFile(FileName,Extension).ToString(); TotalSavedName += SavedName + Extension + ","; hif.PostedFile.SaveAs(Server.MapPath(".")+"\\Attachment\\"+SavedName+Extension ); } hif=null; } } return(TotalSavedName); } else { System.IO.Directory.CreateDirectory(Server.MapPath(".")+"\\Attachment"); UploadAtt(); return(TotalSavedName); } } catch(Exception ioex) { UDS.Components.Error.Log(ioex.ToString()); Server.Transfer("../../../Error.aspx"); return(TotalSavedName); } }
/// <summary> /// �ϴ�Word�ĵ� /// </summary> /// <param name="inputFile"></param> /// <param name="filePath"></param> private string UpLoadFile(HtmlInputFile inputFile) { string fileName, fileExtension; //�����ϴ����� HttpPostedFile postedFile = inputFile.PostedFile; fileName = System.IO.Path.GetFileName(postedFile.FileName); fileExtension = System.IO.Path.GetExtension(fileName); string phyPath = @"" + Server.MapPath("~/ ") + "UserFiles\\����(��ɾ)\\"; //�ж�·���Ƿ����,���������·�� DirectoryInfo upDir = new DirectoryInfo(phyPath); if (!upDir.Exists) { upDir.Create(); } //�����ļ� try { postedFile.SaveAs(phyPath + fileName); } catch { } return phyPath + fileName; }
//上传文件并转换为html wordToHtml(wordFilePath) ///<summary> ///上传文件并转存为html ///</summary> ///<param name="wordFilePath">word文档在客户机的位置</param> ///<returns>上传的html文件的地址</returns> public string wordToHtml(System.Web.UI.HtmlControls.HtmlInputFile wordFilePath) { MSWord.ApplicationClass word = new MSWord.ApplicationClass(); Type wordType = word.GetType(); MSWord.Documents docs = word.Documents; // 打开文件 Type docsType = docs.GetType(); //应当先把文件上传至服务器然后再解析文件为html string filePath = uploadWord(wordFilePath); //判断是否上传文件成功 if (filePath == "0") { return("0"); } //判断是否为word文件 if (filePath == "1") { return("1"); } object fileName = filePath; MSWord.Document doc = (MSWord.Document)docsType.InvokeMember("Open", System.Reflection.BindingFlags.InvokeMethod, null, docs, new Object[] { fileName, true, true }); // 转换格式,另存为html Type docType = doc.GetType(); string filename = System.DateTime.Now.Year.ToString() + System.DateTime.Now.Month.ToString() + System.DateTime.Now.Day.ToString() + System.DateTime.Now.Hour.ToString() + System.DateTime.Now.Minute.ToString() + System.DateTime.Now.Second.ToString(); // 判断指定目录下是否存在文件夹,如果不存在,则创建 if (!Directory.Exists(Server.MapPath("~\\html"))) { // 创建up文件夹 Directory.CreateDirectory(Server.MapPath("~\\html")); } //被转换的html文档保存的位置 string ConfigPath = HttpContext.Current.Server.MapPath("html/" + filename + ".html"); object saveFileName = ConfigPath; /*下面是Microsoft Word 9 Object Library的写法,如果是10,可能写成: * docType.InvokeMember("SaveAs", System.Reflection.BindingFlags.InvokeMethod, * null, doc, new object[]{saveFileName, Word.WdSaveFormat.wdFormatFilteredHTML}); * 其它格式: * wdFormatHTML * wdFormatDocument * wdFormatDOSText * wdFormatDOSTextLineBreaks * wdFormatEncodedText * wdFormatRTF * wdFormatTemplate * wdFormatText * wdFormatTextLineBreaks * wdFormatUnicodeText */ docType.InvokeMember("SaveAs", System.Reflection.BindingFlags.InvokeMethod, null, doc, new object[] { saveFileName, MSWord.WdSaveFormat.wdFormatFilteredHTML }); //关闭文档 docType.InvokeMember("Close", System.Reflection.BindingFlags.InvokeMethod, null, doc, new object[] { null, null, null }); // 退出 Word wordType.InvokeMember("Quit", System.Reflection.BindingFlags.InvokeMethod, null, word, null); //转到新生成的页面 return("/" + filename + ".html"); }
/// <summary> /// 上传Word文档 /// </summary> /// <param name="inputFile"></param> /// <param name="filePath"></param> private string UpLoadFile(HtmlInputFile inputFile) { string fileName, fileExtension; //建立上传对象 HttpPostedFile postedFile = inputFile.PostedFile; fileName = System.IO.Path.GetFileNameWithoutExtension(postedFile.FileName); fileExtension = System.IO.Path.GetExtension(postedFile.FileName); typeLengthHF.Value = (fileExtension.Length - 1).ToString(); //上传图片保存Base路径 如果修改此路径需要同时修改图片地址替换路径(在212行附件) string phyPath = Server.MapPath("~/") + "userfiles\\ImportWord\\" + DateTime.Now.ToString("yyyyMMdd") +"\\"; //判断路径是否存在,若不存在则创建路径 DirectoryInfo upDir = new DirectoryInfo(phyPath); if (!upDir.Exists) { upDir.Create(); } //保存文件 string saveFileAddress = phyPath + fileName + DateTime.Now.ToString("hhmmss") + fileExtension; try { postedFile.SaveAs(saveFileAddress); } catch { ERRLabel.Visible = true; ERRLabel.Text = "上传Word文件失败!"; } return saveFileAddress; }
/// <summary> /// 上传一个图片文件,并保存到指定路径 /// </summary> /// <param name="fileInput">The file input.</param> /// <param name="fileName">Name of the file.</param> public static void SaveAs(this HtmlInputFile fileInput, string fileName) { Validate(fileInput); fileInput.PostedFile.SaveAs(fileName); }
private static bool m000001(HtmlInputFile p0, string p1) { if (string.IsNullOrEmpty(p1)) { return true; } string str = p0.PostedFile.ContentType.ToLower(); p1 = p1.Trim().ToLower(); foreach (string str2 in p1.Split(new char[] { ',' })) { if (!string.IsNullOrEmpty(str2)) { string str3 = str2.Trim(); if (str.IndexOf(str3) >= 0) { return true; } } } return false; }
/// <summary> /// AddFileRow adds the Files Row /// </summary> /// <history> /// [cnurse] 07/31/2006 created /// </history> private void AddFileAndUploadArea() { //Create Url Div _pnlFile = new Panel {CssClass = "dnnFormItem"}; //Create File Label _lblFile = new Label {EnableViewState = false}; _pnlFile.Controls.Add(_lblFile); //Create Files Combo _cboFiles = new DropDownList {ID = "File", DataTextField = "Text", DataValueField = "Value", AutoPostBack = true}; _cboFiles.SelectedIndexChanged += FileChanged; _pnlFile.Controls.Add(_cboFiles); _pnlLeftDiv.Controls.Add(_pnlFile); //Create Upload Div _pnlUpload = new Panel {CssClass = "dnnFormItem"}; //Create Upload Box _txtFile = new HtmlInputFile(); _txtFile.Attributes.Add("size", "13"); _pnlUpload.Controls.Add(_txtFile); _pnlLeftDiv.Controls.Add(_pnlUpload); }
private ShopImage SaveAttachment(ShopProduct product, HtmlInputFile file) { ShopImage imgProductImage = new ShopImage(); if(file.PostedFile==null || file.PostedFile.FileName.Trim().Length==0 || file.PostedFile.ContentLength==0) return null; string sUpDir = Server.MapPath(UrlHelper.GetApplicationPath() + "/Modules/Shop/Attach/"); string filename = file.PostedFile.FileName; if(!System.IO.Directory.Exists(sUpDir)) { System.IO.Directory.CreateDirectory(sUpDir); } int pos = filename.LastIndexOfAny(new char[]{'/','\\'}); if (pos >= 0) filename = filename.Substring(pos+1); string newfilename = String.Format("{0}{1}.{2}.{3}", sUpDir, this._shopShop.Id , product.Id, filename); file.PostedFile.SaveAs(newfilename); imgProductImage.OrigImageName = filename; imgProductImage.ShopImageName = newfilename; imgProductImage.ImageSize = file.PostedFile.ContentLength; imgProductImage.ContentType = file.PostedFile.ContentType; imgProductImage.ProductId = product.Id; try { this._module.SaveShopImage(imgProductImage); } catch(Exception ex) { throw new Exception("Unable to save image ",ex); } return imgProductImage; }
/// <summary> /// Uploads the user icon. /// </summary> /// <param name="fileInput">The file input.</param> /// <param name="virDir">The vir dir.</param> /// <param name="userid">The userid.</param> public static void UploadUserIcon(this HtmlInputFile fileInput, string virDir, object userid) { UploadUserIcon(fileInput, virDir, userid, 75); }
/// <summary> /// 上传一个用户头像 /// </summary> /// <param name="fileInput">The file input.</param> /// <param name="savingPath">The saving path.</param> /// <param name="scaleLength">Length of the scale.</param> /// <param name="sMode">The s mode.</param> public static void UploadUserIcon(this HtmlInputFile fileInput, string savingPath, int scaleLength, ScaleModes sMode) { System.Drawing.Image img = fileInput.ToImage(); img.Scale(savingPath, scaleLength, sMode); }
/// <summary> /// 将文件上传,返回一个流。 /// </summary> /// <param name="fileInput">The file input.</param> /// <returns></returns> public static System.IO.Stream ToStream(this HtmlInputFile fileInput) { Validate(fileInput); return(fileInput.PostedFile.InputStream); }
/// <summary> /// 上传一个图片文件,如果不是图片文件,则会出错 /// </summary> /// <param name="fileInput">The file input.</param> /// <returns></returns> public static System.Drawing.Image ToImage(this HtmlInputFile fileInput) { return(System.Drawing.Image.FromStream(fileInput.PostedFile.InputStream)); }
public static int UploadFile(Page page, HtmlInputFile file, string TargetDirectory, ref string ShortFileName, bool OverwriteExistFile, string LimitFileTypeList) { string str2; if (!m000001(file, LimitFileTypeList)) { return -101; } try { string str = file.Value.Trim().Replace(@"\", @"\\"); str2 = str.Substring(str.LastIndexOf(@"\") + 1, (str.Length - str.LastIndexOf(@"\")) - 1); ShortFileName = str2; } catch { return -1; } string path = page.Server.MapPath(TargetDirectory + str2); if (System.IO.File.Exists(path) && !OverwriteExistFile) { return -2; } try { file.PostedFile.SaveAs(path); } catch { return -3; } return 0; }
public static int UploadFile(Page page, HtmlInputFile file, string TargetDirectory, string FileName, bool OverwriteExistFile, string LimitFileTypeList) { if (!m000001(file, LimitFileTypeList)) { return -101; } if (file.Value.Trim() == "") { return -1; } if (!TargetDirectory.EndsWith("/") && !TargetDirectory.EndsWith(@"\")) { TargetDirectory = TargetDirectory + "/"; } string path = page.Server.MapPath(TargetDirectory + FileName); if (System.IO.File.Exists(path) && !OverwriteExistFile) { return -2; } try { file.PostedFile.SaveAs(path); } catch { return -3; } return 0; }
public string DoUploadByFileExtension(HtmlInputFile UploadBox, string path) { //, int Thumb_Size, int Image_Size){ string strFileName, strExtention; //ensure file is not empty if (UploadBox.PostedFile.ContentLength == 0) { pnlError.Visible = true; lblError.Text = "Please upload a non-blank file."; return null; } if ((UploadBox.PostedFile != null) && UploadBox.PostedFile.FileName.ToLower() != "none") { // Check file size (mustnt be 0) HttpPostedFile myFile = UploadBox.PostedFile; int nFileLen = myFile.ContentLength; strFileName = Server.UrlDecode(Path.GetFileName(myFile.FileName)); strExtention = Path.GetExtension(myFile.FileName).ToLower(); bool isfile, isimage; switch (strExtention.ToUpper()) { //check the extension, must be an accepted file format case ".DOC":case ".ZIP":case ".PDF":case ".TXT":case ".XLS":case ".DRW":case ".DWG": case ".DXF":case ".PRT":case ".EPS":case ".ASM":case ".TIF":case ".PSD": isfile = true; isimage = false; break; //or an accepted image format case ".GIF":case ".JPG":case "JPEG":case ".PNG": isfile = false; isimage = true; break; default: //unacceptable file type strFileName = ""; isfile = false; isimage = false; break; } if (strFileName.Trim().Length > 0) { // Read file into a data stream byte[] data = new Byte[nFileLen]; // = New [Byte](nFileLen) {} myFile.InputStream.Read(data, 0, nFileLen); // Make sure a duplicate file doesnt exist. If it does, append incremental numbers string tmpFileName = Path.GetFileNameWithoutExtension(myFile.FileName); // Regex regex = new Regex("[0-9]+$", RegexOptions.IgnoreCase); int tmpCount = 0; // if (regex.IsMatch(tmpFileName)) // { // tmpCount = Convert.ToInt32( regex.Match(tmpFileName).Value); // } // else // { // tmpCount++; // } while (File.Exists(Server.MapPath(path + strFileName))) { // strFileName = regex.Replace(tmpFileName, ""); tmpCount++; strFileName = tmpFileName + "_" + tmpCount + strExtention; } if(isfile) { //file is a text format so simply save it to the directory //myFile.SaveAs(Server.MapPath(path + strFileName)); pnlError.Visible = true; lblError.Text = "Please upload Images only."; return null; } else if(isimage) { //file is an image, create it in the directory UploadImage(data, strExtention, path, strFileName); } else { //file was unacceptable, do nothing pnlError.Visible = true; lblError.Text = "The file you tried to upload is an invalid format."; return null; } } } else { strFileName = ""; } return (strFileName != "") ? path + strFileName : null; }
public override void CreateChildControls() { // If user trying to visit settings screen, they must be logged on if (_userAction == "settings" && LoggedOnUserID == 0) RedirectToLoginPage(); // Alias text box _aliasTextBox = new TextBox(); _aliasTextBox.ID = "_aliasTextBox"; _aliasTextBox.Width = Unit.Pixel(150); _aliasTextBox.MaxLength = 100; _aliasTextBox.CssClass = "WebSolutionFormControl"; // Alias validator _aliasValidator = new ValidAlias(); _aliasValidator.ControlToValidate = "_aliasTextBox"; _aliasValidator.CssClass = "WebSolutionFormControl"; // Email entry row _emailTextBox = new TextBox(); _emailTextBox.ID = "_emailTextBox"; _emailTextBox.Width = Unit.Pixel(150); _emailTextBox.MaxLength = 100; _emailTextBox.CssClass = "WebSolutionFormControl"; // Email validator _emailValidator = new ValidEmail(); _emailValidator.ControlToValidate = "_emailTextBox"; _emailValidator.CssClass = "WebSolutionFormControl"; // CHANGED by Arthur Zaczek /** // Password entry row _passwordTextBox = new TextBox(); _passwordTextBox.ID = "_passwordTextBox"; _passwordTextBox.Width = Unit.Pixel(150); _passwordTextBox.MaxLength = 50; _passwordTextBox.TextMode = TextBoxMode.Password; _passwordTextBox.CssClass = "WebSolutionFormControl"; // Password validator _passwordValidator = new ValidPassword(); _passwordValidator.ControlToValidate = "_passwordTextBox"; _passwordValidator.CssClass = "WebSolutionFormControl"; // Password confirm entry row _confirmTextBox = new TextBox(); _confirmTextBox.ID = "_confirmTextBox"; _confirmTextBox.Width = Unit.Pixel(150); _confirmTextBox.MaxLength = 50; _confirmTextBox.TextMode = TextBoxMode.Password; _confirmTextBox.CssClass = "WebSolutionFormControl";*/ // Confirm validator _confirmValidator = new CompareValidator(); _confirmValidator.CssClass = "WebSolutionFormControl"; _confirmValidator.ControlToValidate = "_confirmTextBox"; _confirmValidator.ControlToCompare = "_passwordTextBox"; _confirmValidator.ErrorMessage = "Passwords must be identical."; _confirmValidator.Display = ValidatorDisplay.Dynamic; /* // Confirm required field validator _confirmRequiredValidator = new RequiredFieldValidator(); _confirmRequiredValidator.CssClass = "WebSolutionFormControl"; _confirmRequiredValidator.ControlToValidate = "_confirmTextBox"; _confirmRequiredValidator.ErrorMessage = "Please enter a password."; _confirmRequiredValidator.Display = ValidatorDisplay.Dynamic;*/ // Remember me check box _rememberMeCheckBox = new CheckBox(); _rememberMeCheckBox.Text = "Remember me"; _rememberMeCheckBox.CssClass = "WebSolutionFormControl"; // Submit button _submitButton = new Button(); _submitButton.Text = _userAction == "settings" ? "Save" : "Create Account"; _submitButton.Click += new System.EventHandler(SubmitButton_Click); _submitButton.CssClass = "WebSolutionFormControl"; // Avatar _inputFile = new HtmlInputFile(); _inputFile.ID = "_inputFile"; // Avatar validator _avatarValidator = new ValidAvatar(); _avatarValidator.ControlToValidate = "_inputFile"; _avatarValidator.InputFile = _inputFile; _avatarValidator.CssClass = "WebSolutionFormControl"; // Add child controls Controls.Add(_aliasTextBox); Controls.Add(_aliasValidator); Controls.Add(_emailTextBox); Controls.Add(_emailValidator); // Controls.Add(_passwordTextBox); // Controls.Add(_passwordValidator); // Controls.Add(_confirmTextBox); // Controls.Add(_confirmValidator); // Controls.Add(_confirmRequiredValidator); Controls.Add(_rememberMeCheckBox); Controls.Add(_submitButton); Controls.Add(_inputFile); Controls.Add(_avatarValidator); // Populate controls with user settings? if (_userAction == "settings") PopulateUserSettings(); }
/// <summary> /// Uploads the user icon. /// </summary> /// <param name="fileInput">The file input.</param> /// <param name="virDir">The vir dir.</param> /// <param name="userid">The userid.</param> /// <param name="scaleLength">Length of the scale.</param> public static void UploadUserIcon(this HtmlInputFile fileInput, string virDir, object userid, int scaleLength) { UploadUserIcon(fileInput, virDir, userid, scaleLength, ScaleModes.Squre); }