private void FileUpload(System.Web.UI.WebControls.FileUpload iFile) { string virtualPath = "../images/stg/"; string absolutePath = Server.MapPath(virtualPath); string fullFilePath = ""; if (!Directory.Exists(absolutePath)) { DirectoryInfo objFold = Directory.CreateDirectory(absolutePath); absolutePath = objFold.FullName; } if (this.IType == "D") { fullFilePath = absolutePath + hdfImagePath.Value; if (File.Exists(fullFilePath)) { File.Delete(fullFilePath); } } else { fullFilePath = absolutePath + iFile.FileName; if (File.Exists(fullFilePath)) { File.SetAttributes(fullFilePath, FileAttributes.Normal); File.Delete(fullFilePath); } iFile.SaveAs(fullFilePath); } }
public void UpLoad(string path, System.Web.UI.WebControls.FileUpload fileupload) { bool fileOK = false; if (fileupload.HasFile) { string fileException = System.IO.Path.GetExtension(fileupload.FileName).ToLower(); string[] allowedException = { ".docx", ".xlsx", ".xls", ".doc", ".mpp", ".rar", ".zip", ".vsd", ".txt", ".jpg", ".gif", ".bmp", ".png", ".swf", ".avi", ".mp3", ".rm", ".wma", ".wmv" }; for (int i = 0; i < allowedException.Length; i++) { if (fileException == allowedException[i]) { fileOK = true; } } } if (fileOK) { //判断文件是否存在,不存在则创建路径 if (System.IO.Directory.Exists(path)) { //该目录存在,则将上传的文件保存在该目录当中; } else { System.IO.Directory.CreateDirectory(path); } fileupload.SaveAs(path + "\\" + fileupload.FileName); } else { throw new Exception("不支持此格式文件上传!"); } }
protected void InsertButton_Click(object sender, EventArgs e) { if (FileUpload1.HasFile) { try { string fn = System.IO.Path.GetFileName(FileUpload1.FileName); string SaveLocation = Server.MapPath("~/Content/Upload") + "\\" + fn; FileUpload1.SaveAs(SaveLocation); Response.Write("The file has been uploaded."); //FileUpload1.SaveAs("C:\\Uploads\\" + // FileUpload1.FileName); //Label1.Text = "File name: " + // FileUpload1.PostedFile.FileName + "<br>" + // FileUpload1.PostedFile.ContentLength + " kb<br>" + // "Content type: " + // FileUpload1.PostedFile.ContentType; } catch (Exception ex) { Response.Write("Error: " + ex.Message); } } else { Response.Write("eheeeeeeeeein"); } }
public static string UploadFile(FileUpload fileUpload) { if (fileUpload == null) { return string.Empty; } var tempMediaPath = ConfigurationHelper.GetScrudParameter("TempMediaPath"); var uploadDirectory = HttpContext.Current.Server.MapPath(tempMediaPath); if (!Directory.Exists(uploadDirectory)) { Directory.CreateDirectory(uploadDirectory); } var id = Guid.NewGuid().ToString(); if (fileUpload.HasFile) { id += Path.GetExtension(fileUpload.FileName); id = Path.Combine(uploadDirectory, id); fileUpload.SaveAs(id); } return id; }
public string fileupload(string name, int id) { string fileth = ""; string str = ""; string fid = name; if (File(name)) { if (PdMusic(fid)) { fid = name.Substring(0, name.LastIndexOf('.')) + "_IMG" + DateTime.Now.ToString("yyyyHHmmssfff") + Path.GetExtension(name); } fileth = "~/upload/images/" + fid; FileInfo filee = new FileInfo(Server.MapPath(fileth));//删除以前的老文件 if (filee.Exists) { filee.Delete(); } FileUpload FiLe = new FileUpload(); FiLe.SaveAs(Server.MapPath(fileth)); //判断是修改状态,还是添加状态 if (id == 0)//添加 { } else {//修改 Daxu.Entity.newlist newlistInfo = new Daxu.Entity.newlist(); newlistInfo.cnen = fid; Daxu.BLL.newlistBll.UpdateInewlist(newlistInfo); } str = fid; } return str; // return "你好!"; }
/// <summary> /// 文件上传(asp:FileUpload的对象myControl,服务器地址severUrl) /// </summary> /// <param name="myControl"></param> /// <param name="severUrl"></param> /// <returns></returns> public static bool SaveImg(System.Web.UI.WebControls.FileUpload myControl, string severUrl, string picName) { //获取文件的后缀名picLastName string localUrl = myControl.PostedFile.FileName;//获取上传的文件路径(本地路径) int index = localUrl.LastIndexOf("."); string picLastName = localUrl.Substring(index); if (picLastName != ".jpeg" && picLastName != ".jpg" && picLastName != ".gif" && picLastName != ".png" && picLastName != ".bmp") { return(false); } //上传后的文件名 string pictureName = null; pictureName = picName + picLastName; try { myControl.SaveAs(severUrl + "/" + pictureName); return(true); } catch (Exception ex) { return(false); } }
/// <summary> /// 上传图片 /// </summary> /// <param name="fuControl"></param> /// <returns></returns> private string UploadPhoto(System.Web.UI.WebControls.FileUpload fuControl) { #region 图片功能 string photoName = ""; try { //图片文件夹 string rootDir = Server.MapPath("../../upload/labUploadFiles/"); //上传图片,生成文件保存目录名 string fileName = new FileInfo(fuControl.FileName).Name; //当前时间,精确到毫秒6位 string randomName = DateTime.Now.ToString("yyyyMMddHHmmffffff"); photoName = randomName + fileName.Substring(fileName.IndexOf(".")); //文件存放到程序上的路径 string fileDir = rootDir + "/" + photoName; fuControl.SaveAs(fileDir); return(photoName); } catch (Exception ex) { MessageBoxShow(ex.Message, MessageBoxIcon.Error); return(photoName); } #endregion }
public static string UploadFile(FileUpload fileUpload) { if (fileUpload == null) { return string.Empty; } //Todo: Parameterize media path. string uploadDirectory = HttpContext.Current.Server.MapPath("~/Media/Temp"); if (!System.IO.Directory.Exists(uploadDirectory)) { System.IO.Directory.CreateDirectory(uploadDirectory); } string id = Guid.NewGuid().ToString(); if (fileUpload.HasFile) { id += System.IO.Path.GetExtension(fileUpload.FileName); id = System.IO.Path.Combine(uploadDirectory, id); fileUpload.SaveAs(id); } return id; }
public static Guid UploadAttach(FileUpload fu) { if (!fu.HasFile || fu.FileName.Length == 0) { throw new BusinessObjectLogicException("Please select upload file!"); } string path = null; try { string subDirectory = DateTime.Now.ToString("yyyyMM") + Path.DirectorySeparatorChar + DateTime.Now.ToString("dd"); string directory = System.Configuration.ConfigurationManager.AppSettings["File"] + subDirectory; if (!Directory.Exists(directory)) Directory.CreateDirectory(directory); string title = Path.GetFileNameWithoutExtension(fu.FileName); string ext = Path.GetExtension(fu.FileName); path = Path.DirectorySeparatorChar + Path.GetRandomFileName() + ext; fu.SaveAs(directory + path); Attachment attach = new Attachment(UserHelper.UserName); attach.Title = title; attach.Path = subDirectory + path; new AttachmentBl().AddAttach(attach); return attach.UID; } catch { throw new BusinessObjectLogicException("File upload fail!"); } }
public string img(FileUpload upload) { string str = ""; string filename = upload.FileName; if (filename.Equals("")) { MessShowBox.show("图片不能为空", this); } else { string type = filename.Substring(filename.LastIndexOf(".") + 1).ToLower(); if (type == "jpg" || type == "bmp" || type == "gif" || type == "png") { str = "/public/user_img/" + DateTime.Now.ToString("yyyyMMddhhmmss") + filename; if (!File.Exists(filename)) { upload.SaveAs(MapPath(str)); } else { MessShowBox.show("文件已存在,请重命名后再上传", this); } } else { MessShowBox.show("上传的图片个是不正确,图片格式必须是|jpg|bmp|gif|png", this); } } return str; }
public static bool DosyaKaydet(this System.Web.UI.WebControls.FileUpload fileupload, string yol, out string dosya, out string mesaj) { mesaj = ""; dosya = yol; if (fileupload.HasFile) { string dosyamiz = fileupload.FileName.ToLower(); try { string resimurl = ClassBLL.ZamanaGoreResimAdiGetir(); dosya += "/" + resimurl; string yeniyol = System.Web.HttpContext.Current.Server.MapPath(yol) + "\\" + resimurl; fileupload.SaveAs(yeniyol); return(true); } catch (Exception exc) { mesaj = exc.Message; } return(false); } return(false); }
//Try uploading the image for decryption public static IMAGE_UPLOAD_RESULT UploadImage(System.Web.UI.WebControls.FileUpload fileUpload, ref string _name) { IMAGE_UPLOAD_RESULT result = IMAGE_UPLOAD_RESULT.SUCCESS; //Get the file name string filename = Path.GetFileName(fileUpload.FileName); //Generate a new random name (GUID) for the image filename = Guid.NewGuid().ToString() + "_" + filename; //Save the file in the proper path with the proper name fileUpload.SaveAs(FolderPath + filename); //Check is it's not an image if (!isImage(FolderPath + filename)) { result = IMAGE_UPLOAD_RESULT.FAILED; } else { //If it's an image try { //Read the image data to check if it's valid using (System.Drawing.Image myImage = System.Drawing.Image.FromStream(fileUpload.PostedFile.InputStream)) { /* //If it's not a square * if (myImage.Height != myImage.Width) * { * //Display error because image isn't square * result = IMAGE_UPLOAD_RESULT.DIMNOTEQUAL; * }*/ //Check if the image width is greater than the maximum width allowed (for memroy reasons) if (myImage.Width > MAXWIDTH) { //Display error because image is too big result = IMAGE_UPLOAD_RESULT.BIGFILE; } } } catch (Exception exp) { //Display error because uploading has failed result = IMAGE_UPLOAD_RESULT.FAILED; } } //If uploading was a success, set _name to the filename if (result == IMAGE_UPLOAD_RESULT.SUCCESS) { _name = filename; } else { //If it wasn't successful, delete the uploaded file DeleteFile(FolderPath + filename); } //Return the upload result return(result); }
public void SaveFile(string destination, System.Web.UI.WebControls.FileUpload file) { if (file.HasFile) { file.SaveAs(destination + file.FileName); file.Dispose(); } }
private string SaveFileToTemp(string fileName,FileUpload f) { if (f.FileName.EndsWith("xls")) { f.SaveAs(TempPath + "\\"+fileName+".xls"); return TempPath + "\\"+fileName+".xls"; } else if (f.FileName.EndsWith("xlsx")) { f.SaveAs(TempPath + "\\"+fileName+".xlsx"); return TempPath + "\\"+fileName+".xlsx"; } else return null; }
/// <summary> /// 1:上傳檔案格式請參考:UI Spec Excel檔案格式。 /// 2:檢查檔案Size大於0等必要檢查。 /// 3:上傳檔案到AP_Server端暫存路徑,如有任何異常,則回傳錯誤訊息停止上傳流程。 /// </summary> public ArrayList FileUpload(string s_UploadPath, FileUpload File_Upload, string s_LoginUser) { try { #region 宣告變數 String s_fileExtension = string.Empty;//副檔名 String s_fileWithoutExtension = string.Empty;//檔名不包含副檔名 DateTime d_CreateDate = DateTime.Now; ArrayList arl_Return = new ArrayList(); bool b_fileOK = false; #endregion # region 檢查上傳檔案的路徑與檔案格式 s_fileExtension = System.IO.Path.GetExtension(File_Upload.FileName).ToLower();//副檔名 s_fileWithoutExtension = System.IO.Path.GetFileNameWithoutExtension(File_Upload.FileName).ToLower();//檔名 if (File_Upload.HasFile) { String[] allowedExtensions ={ ".xls" };//在此設定允許上傳的檔案格式 for (int i = 0; i < allowedExtensions.Length; i++) { if (s_fileExtension == allowedExtensions[i]) { b_fileOK = true; } } } #endregion #region 將檔案上傳至AP if (b_fileOK == true) { //儲存的新檔名=原檔名_登入者_上傳時間.副檔名 s_UploadPath += s_fileWithoutExtension + "_" + s_LoginUser + "_" + d_CreateDate.ToString("yyyyMMddHHmmss") + s_fileExtension; File_Upload.SaveAs(s_UploadPath); arl_Return.Add("TRUE"); arl_Return.Add(s_UploadPath); arl_Return.Add(d_CreateDate); arl_Return.Add(s_fileWithoutExtension + "_" + s_LoginUser + "_" + d_CreateDate.ToString("yyyyMMddHHmmss") + s_fileExtension); } else { arl_Return.Add("FALSE"); arl_Return.Add("路徑" + File_Upload.PostedFile.FileName + "不是正確的檔案"); } #endregion return arl_Return; } catch (Exception ex) { throw ex; } }
public static string SaveFile(FileUpload fileUploader, string filename, string directory) { CheckDirectory(GetServerDirectoryPath(directory)); string absoluteDirectoryPath = GetAbsoluteDirectoryPath(filename, directory); fileUploader.SaveAs(GetServerDirectoryPath(absoluteDirectoryPath)); return absoluteDirectoryPath; }
protected bool checkPhoto(FileUpload imgFU,int catagoryid,int itemid) { System.Drawing.Image img = null;//System.Drawing.Image.FromStream(PhotoFU.PostedFile.InputStream); //Image uploadedImage = null; if (imgFU.HasFile && imgFU.FileName != string.Empty && imgFU.FileContent.Length > 0) { if (imgFU.FileContent.Length <= 1024000) { try { img = System.Drawing.Image.FromStream(imgFU.PostedFile.InputStream); if (img.RawFormat.Guid == System.Drawing.Imaging.ImageFormat.Jpeg.Guid || img.RawFormat.Guid == System.Drawing.Imaging.ImageFormat.Png.Guid || img.RawFormat.Guid == System.Drawing.Imaging.ImageFormat.Gif.Guid) { //replace the old image with new image string filename = itemid + "Photo.jpg"; imgFU.SaveAs(Server.MapPath("~/ItemImages/" + catagoryid + "/" + itemid + "/") + filename); string filePath = Server.MapPath("~/ItemImages/" + catagoryid + "/" + itemid + "/") + filename; string newfileMed = itemid + "Photomedium.jpg"; string newfileSmall = itemid + "small.jpg"; string resizedImageMed = Server.MapPath("~/ItemImages/" + catagoryid + "/" + itemid + "/") + newfileMed; string resizedImageSmall = Server.MapPath("~/ItemImages/" + catagoryid + "/" + itemid + "/") + newfileSmall; System.Drawing.Image img1 = System.Drawing.Image.FromFile(filePath); System.Drawing.Bitmap bmpD = img1 as Bitmap; Bitmap bmpDriverMed = new Bitmap(bmpD, 512, 372); bmpDriverMed.Save(resizedImageMed, System.Drawing.Imaging.ImageFormat.Jpeg); Bitmap bmpDriverSmall = new Bitmap(bmpD, 170, 126); bmpDriverSmall.Save(resizedImageSmall, System.Drawing.Imaging.ImageFormat.Jpeg); return true; } else { lbl_status.Text = "Selected file is not an image"; return false; } } catch (Exception ex) { lbl_status.Text = "Selected file is not an image.<br />" + ex.Message; return false; } } else { lbl_status.Text = "File is too Large. only 1mb allowed"; return false; } } else return true; }
public ArrayList FileUpload(string s_UploadPath, FileUpload File_Upload, string s_LoginUser) { #region String s_fileExtension = string.Empty;//副檔名 String s_fileWithoutExtension = string.Empty;//檔名不包含副檔名 DateTime d_CreateDate = DateTime.Now; ArrayList arl_Return = new ArrayList(); bool b_fileOK = false; # region 檢查上傳檔案的路徑與檔案格式 s_fileExtension = System.IO.Path.GetExtension(File_Upload.FileName).ToLower();//副檔名 s_fileWithoutExtension = System.IO.Path.GetFileNameWithoutExtension(File_Upload.FileName).ToLower();//檔名 if (File_Upload.HasFile) { String[] allowedExtensions ={ ".xls", ".XLS" };//在此設定允許上傳的檔案格式 for (int i = 0; i < allowedExtensions.Length; i++) { if (s_fileExtension == allowedExtensions[i]) { b_fileOK = true; } } } #endregion #region 將檔案上傳至AP if (b_fileOK == true) { s_UploadPath += s_fileWithoutExtension + "_" + s_LoginUser + "_" + d_CreateDate.ToString("yyyyMMddHHmmss") + s_fileExtension; File_Upload.SaveAs(s_UploadPath); arl_Return.Add("TRUE"); arl_Return.Add(s_UploadPath); arl_Return.Add(d_CreateDate); arl_Return.Add(s_fileWithoutExtension + "_" + s_LoginUser + "_" + d_CreateDate.ToString("yyyyMMddHHmmss") + s_fileExtension); arl_Return.Add(s_fileWithoutExtension); } else { arl_Return.Add("FALSE"); arl_Return.Add("上傳檔案不是xls檔"); } #endregion return arl_Return; #endregion }
/// <summary> /// 工具方法:上传文件的方法 /// </summary> /// <param name="myFileUpload">上传控件的ID</param> /// <param name="allowExtensions">允许上传的扩展文件名类型,如:string[] allowExtensions = { ".doc", ".xls", ".ppt", ".jpg", ".gif" };</param> /// <param name="maxLength">允许上传的最大大小,以M为单位</param> /// <param name="savePath">保存文件的目录,注意是绝对路径,如:Server.MapPath("~/upload/");</param> /// <param name="saveName">保存的文件名,如果是""则以原文件名保存</param> public static string FilesUpload(FileUpload myFileUpload, string[] allowExtensions, int maxLength, string savePath, string saveName) { // 文件格式是否允许上传 bool fileAllow = false; //检查是否有文件案 if (myFileUpload.HasFile) { // 检查文件大小, ContentLength获取的是字节,转成M的时候要除以2次1024 if (myFileUpload.PostedFile.ContentLength / 1024 / 1024 >= maxLength) { return String.Format("只能上传小于{0}M的文件!",maxLength); } //取得上传文件之扩展文件名,并转换成小写字母 string fileExtension = System.IO.Path.GetExtension(myFileUpload.FileName).ToLower(); string tmp = ""; // 存储允许上传的文件后缀名 //检查扩展文件名是否符合限定类型 for (int i = 0; i < allowExtensions.Length; i++) { tmp += i == allowExtensions.Length - 1 ? allowExtensions[i] : allowExtensions[i] + ","; if (fileExtension == allowExtensions[i]) { fileAllow = true; } } if (allowExtensions.Length == 0) { fileAllow = true; } if (fileAllow) { try { DirectoryInfo di = new DirectoryInfo(Path.GetFullPath(savePath)); if (!di.Exists) { di.Create(); } string path = savePath + (saveName == "" ? myFileUpload.FileName : saveName); //存储文件到文件夹 myFileUpload.SaveAs(path); } catch (Exception ex) { throw new Exception(ex.Message); } } else { return "文件格式不符,可以上传的文件格式为:" + tmp; } } else { return "请选择要上传的文件!"; } return ""; }
public static string UploadFile(this System.Web.UI.WebControls.FileUpload file, string directorypath) { if (!file.HasFile) { return(null); } var fileName = Guid.NewGuid() + "_" + file.FileName; file.SaveAs(directorypath + fileName); return(fileName); }
public static string UploadFile(this System.Web.UI.WebControls.FileUpload file, string directorypath, string filename) { if (!file.HasFile) { return(null); } if (filename.Trim().Length == 0) { return(file.UploadFile(directorypath)); } file.SaveAs(directorypath + filename); return(filename); }
void btn_Upload_Click(object sender, EventArgs e) { System.Web.UI.WebControls.FileUpload fu = this.Pub1.FindControl("file") as System.Web.UI.WebControls.FileUpload; if (fu.HasFile == false || fu.FileName.Length <= 2) { this.Alert("请选择上传的文件."); return; } Prj prj = new Prj(this.FK_Prj); AtPara ap = new AtPara(prj.Files); string file = ap.GetValStrByKey(this.IDX.ToString()); try { fu.SaveAs(file); } catch { string root = BP.SystemConfig.PathOfDataUser + "\\PrjData\\Templete\\" + this.FK_Prj; string rootData = BP.SystemConfig.PathOfDataUser + "\\PrjData\\Data\\" + this.FK_Prj; if (Directory.Exists(rootData) == false) { Directory.CreateDirectory(rootData); } string[] strs = System.IO.Directory.GetDirectories(root); foreach (string str in strs) { DirectoryInfo info = new DirectoryInfo(str); if (Directory.Exists(rootData + "\\" + info.Name) == false) { Directory.CreateDirectory(rootData + "\\" + info.Name); } } fu.SaveAs(file); } this.WinClose(); }
protected void btnUpload_Click(object sender, EventArgs e) { if (FileUpload3.HasFile) { if (txtFile1.Text.ToString() == "") { //Add file to text box 1 and session Session.Add(Global.Parameters.File3, FileUpload3); String tempFile3 = System.IO.Path.GetDirectoryName(System.IO.Path.GetTempFileName().ToString()); tempFile3 = tempFile3 + "\\" + FileUpload3.FileName.ToString(); Session.Add(Global.Parameters.tempFile3, tempFile3.ToString()); FileUpload3.SaveAs(tempFile3); txtFile1.Text = FileUpload3.FileName.ToString(); } else { if (txtFile2.Text.ToString() == "") { //Add file to text box 2 and session Session.Add(Global.Parameters.File4, FileUpload3); String tempFile4 = System.IO.Path.GetDirectoryName(System.IO.Path.GetTempFileName().ToString()); tempFile4 = tempFile4 + "\\" + FileUpload3.FileName.ToString(); Session.Add(Global.Parameters.tempFile4, tempFile4.ToString()); FileUpload3.SaveAs(tempFile4); txtFile2.Text = FileUpload3.FileName.ToString(); } else { //both files are full display error msg ValidationSummary1.AddErrorMessage("You file limit of 2 has been reached, please delete a file before uploading another. "); } } } else { ValidationSummary1.AddErrorMessage("You must Browse to your file before uploading. "); } }
private string UploadFileAndGetFilePath(FileUpload fileUpload) { string folderPath = Server.MapPath("~/Upload"); IoHelper.ValidateFolderExsistence(folderPath); string filePath = folderPath + @"\" + fileUpload.FileName.ToString(); IoHelper.ValidateFileExsistence(filePath); fileUpload.SaveAs(filePath); return filePath; }
/// <summary> /// 保存文件 /// </summary> /// <param name="file"></param> /// <param name="path">文件路径</param> /// <returns></returns> public static string SaveFile(this System.Web.UI.WebControls.FileUpload file, string path) { if (file.HasFile) { FileInfo info = new FileInfo(file.FileName); string fileName = Guid.NewGuid() + info.Extension; file.SaveAs(Path.Combine(path, fileName)); return(fileName); } else { return(string.Empty); } }
public static string FullPath(FileUpload fileUpload, string AbsolutePath, string TextId, int MaxLength) { string FullPath = ""; if (string.IsNullOrEmpty(AbsolutePath)) AbsolutePath = EnumsFile.Files; if (fileUpload.HasFile) { FullPath = GetFileName(fileUpload.FileName, AbsolutePath, TextId, MaxLength); fileUpload.SaveAs(HttpContext.Current.Server.MapPath("~") + FullPath); } return FullPath; }
public string File_Upload(System.Web.UI.WebControls.FileUpload fp) { string filepath, folderpath, savepath, folderpathnew, savepathnew; folderpath = System.Web.HttpContext.Current.Server.MapPath("Resumes"); folderpathnew = "~\\Resumes"; filepath = Path.GetFileName(fp.PostedFile.FileName); savepath = folderpath + "\\" + filepath; savepathnew = folderpathnew + "\\" + filepath; fp.SaveAs(savepath); return(savepathnew); }
void btn_Click(object sender, EventArgs e) { BP.Sys.FrmAttachment athDesc = new BP.Sys.FrmAttachment(this.FK_FrmAttachment); System.Web.UI.WebControls.FileUpload fu = this.Pub1.FindControl("file") as System.Web.UI.WebControls.FileUpload; if (fu.HasFile == false || fu.FileName.Length <= 2) { this.Alert("请选择上传的文件."); return; } if (System.IO.Directory.Exists(athDesc.SaveTo) == false) { System.IO.Directory.CreateDirectory(athDesc.SaveTo); } int oid = BP.DA.DBAccess.GenerOID(); string exp = ""; string saveTo = athDesc.SaveTo + "\\" + oid + "." + fu.FileName.Substring(fu.FileName.LastIndexOf('.') + 1); fu.SaveAs(saveTo); FileInfo info = new FileInfo(saveTo); FrmAttachmentDB dbUpload = new FrmAttachmentDB(); dbUpload.MyPK = athDesc.FK_MapData + oid.ToString(); dbUpload.FK_FrmAttachment = this.FK_FrmAttachment; dbUpload.RefPKVal = this.PKVal.ToString(); dbUpload.FK_MapData = athDesc.FK_MapData; dbUpload.FileExts = info.Extension; dbUpload.FileFullName = saveTo; dbUpload.FileName = fu.FileName; dbUpload.FileSize = (float)info.Length; dbUpload.RDT = DataType.CurrentDataTime; dbUpload.Rec = BP.Web.WebUser.No; dbUpload.RecName = BP.Web.WebUser.Name; if (athDesc.IsNote) { dbUpload.MyNote = this.Pub1.GetTextBoxByID("TB_Note").Text; } if (athDesc.Sort.Contains(",")) { dbUpload.Sort = this.Pub1.GetDDLByID("ddl").SelectedItemStringVal; } dbUpload.Insert(); this.Response.Redirect("AttachmentUpload.aspx?IsBTitle=" + this.IsBTitle + "&FK_FrmAttachment=" + this.FK_FrmAttachment + "&PKVal=" + this.PKVal, true); }
public static string SaveImage(FileUpload Fu, string prefix, string localImagePath) { if (!Directory.Exists(localImagePath)) Directory.CreateDirectory(localImagePath); string strImage = string.Empty; string SavePath = string.Empty; //SavePath = GetImagePathWithFileName(3, prefix, localImagePath); SavePath = localImagePath; SavePath += '\\' + prefix; Fu.SaveAs(SavePath); Fu.FileContent.Dispose(); strImage = SavePath; //Fu.PostedFile.ContentLength return strImage; }
/// <summary> /// 上传文件 /// </summary> /// <param name="page">页面对象</param> /// <param name="fileload">上传控件</param> /// <param name="strPath">路径</param> public static void UpLoadFile(System.Web.UI.Page page, System.Web.UI.WebControls.FileUpload fileload, string strPath, string strNewName) { string ServerPath = page.Server.MapPath(strPath); if (!Directory.Exists(ServerPath)) { //若文件目录不存在 则创建 Directory.CreateDirectory(ServerPath); } ServerPath += strNewName; try { fileload.SaveAs(ServerPath); } catch (Exception ex) { throw ex; } }
public void Upload_Click(object sender, EventArgs e) { if (FileUploadControl.HasFile) { try { string filename = Path.GetFileName(FileUploadControl.FileName); FileUploadControl.SaveAs(Server.MapPath("~/Temp/") + filename); StatusLabel.Text = "Upload status: File uploaded!"; } catch (Exception ex) { StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message; } } }
private string getImage(FileUpload fa, string oldFile) { if (fa.HasFile) { string file = DateTime.Now.Year + DateTime.Now.Month + DateTime.Now.Second + DateTime.Now.Millisecond + fa.FileName; //create the path to save the file to string fileName = Path.Combine(Server.MapPath("~/images/profiles"), file); //save the file to our local path fa.SaveAs(fileName); return "~/images/profiles/" + file; } else { return oldFile; } }
public static SaveFileResult SaveFile(string strAcct, FileUpload FileUpload, 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 = strAcct + DateTime.Now.ToString("yyMMddHHmmssfff") + Path.GetExtension(FileUpload.FileName); string filename = HttpContext.Current.Server.MapPath(SaveFilePath + str2); FileUpload.SaveAs(filename); FileUpload.Dispose(); result.Result = true; result.Msg = SaveFilePath + str2; } return result; }
//Parameter : Web FileUpload Control public string DefaultNameSave(FileUpload fileUpload) { string result = null; if (fileUpload.Equals(null)) return result; string filename = fileUpload.FileName; if (filename.Equals("")) return result; if (!(new Validate(filename, uploadType).Checked())) return result; string fileExtension = System.IO.Path.GetExtension(filename); result = newName + "_" + System.IO.Path.GetFileNameWithoutExtension(filename) + fileExtension; fileUpload.SaveAs(savePath + result); return result; }
public string insert(FileUpload uploadImagem, Label saida, string caminho) { string teste = ""; //Verifica se arquivo selecionado é um arquivo válido if (uploadImagem.HasFile) { //Verifica tamanho do arquivo if (uploadImagem.PostedFile.ContentLength > 4000000) { saida.Text = "Limite excedido! Selecione Imagem Menor"; } else { //Verifica Extensao do arquivo string verifica = Path.GetExtension(uploadImagem.FileName); if (verifica == ".jpg" || verifica == ".bmp" || verifica == ".png" || verifica == ".gif") { try { //Salva Arquivo de forma criptografada uploadImagem.SaveAs(HttpContext.Current.Server.MapPath(caminho) + md5_encriptar(uploadImagem.FileName) + Path.GetExtension(uploadImagem.FileName)); HttpContext.Current.Response.Redirect(HttpContext.Current.Request.RawUrl); teste = HttpContext.Current.Server.MapPath(caminho) + md5_encriptar(uploadImagem.FileName) + Path.GetExtension(uploadImagem.FileName) + Path.GetExtension(uploadImagem.FileName); } catch (Exception ex) { saida.Text = "Erro: " + ex.Message.ToString(); } } else { saida.Text = "Extensão não suportada! Somente imagens jpg, bmp, png ou gif"; } } } else { saida.Text = "Você deve escolher um arquivo para o upload."; } return teste; }
public static bool resimKaydet(this System.Web.UI.WebControls.FileUpload fileupload, string yol, int boyut, out string resim, out string mesaj) { mesaj = ""; resim = yol; if (fileupload.HasFile) { string tamponresim = fileupload.FileName.ToLower(); if (!tamponresim.EndsWith("jpeg") && !tamponresim.EndsWith("gif") && !tamponresim.EndsWith("png") && !tamponresim.EndsWith("image/pjpeg") && !tamponresim.EndsWith("jpg")) { mesaj = "jpeg, jpg , png, gif formatlarından birini seçiniz..."; return(false); } try { string resimurl = ClassBLL.ZamanaGoreResimAdiGetir(); string[] kelimeler = tamponresim.Split(new string[] { "." }, StringSplitOptions.RemoveEmptyEntries); string uzanti = kelimeler[kelimeler.Length - 1]; resimurl += "." + uzanti; resim += "/" + resimurl; string yeniyol = System.Web.HttpContext.Current.Server.MapPath(yol) + "\\" + resimurl; fileupload.SaveAs(yeniyol); ImageFormat imgformat = uzanti.resimFormati(); ResimBoyutlandir(yeniyol, yeniyol, boyut, imgformat); return(true); } catch (Exception exc) { mesaj = exc.Message; } return(false); } return(false); }
public static void Insert(string title, string author, string content, System.Web.UI.WebControls.FileUpload FU_Image) { Guid guid = Guid.NewGuid(); string url = ""; string ConnectionString = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString; SqlConnection conn = new SqlConnection(ConnectionString); try { if (FU_Image.PostedFile != null) { string fileExtention = Path.GetExtension(FU_Image.FileName.ToLower()); if (fileExtention == ".jpeg" || fileExtention == ".jpg" || fileExtention == ".png") { string FileName = Path.GetFileName(FU_Image.PostedFile.FileName); string rename = guid + FileName.Replace(" ", "_"); FU_Image.SaveAs(System.Web.HttpContext.Current.Server.MapPath("~/pages/news/newsimages/" + rename)); url = "~/pages/news/newsimages/" + rename; } } conn.Open(); using (SqlCommand cmd = new SqlCommand()) { cmd.Connection = conn; cmd.CommandType = CommandType.Text; cmd.CommandText = SQLQuery.NewsInsert; cmd.Parameters.AddWithValue("@Title", title); cmd.Parameters.AddWithValue("@Author", author); cmd.Parameters.AddWithValue("@Content", content); cmd.Parameters.AddWithValue("@CreateDate", String.Format("{0:d/M/yyyy HH:mm:ss}", DateTime.Now)); cmd.Parameters.AddWithValue("@Image", url); cmd.ExecuteNonQuery(); } conn.Close(); } catch (Exception e) { } // // TODO: Add constructor logic here // }
protected void Button1_Click(object sender, EventArgs e) { this.m_FileExtArr = "jpg|gif|png|bmp|jpeg|swf|rar"; string str3 = ""; string foldername = ""; string filename = ""; string str2 = ""; System.Web.UI.WebControls.FileUpload upload = (System.Web.UI.WebControls.FileUpload) this.FindControl("FileUpload1"); StringBuilder builder2 = new StringBuilder(); if (upload.HasFile) { str2 = Path.GetExtension(upload.FileName).ToLower(); if (!this.CheckFilePostfix(str2.Replace(".", ""))) { builder2.Append("照片" + upload.FileName + "不符合图片扩展名规则" + this.m_FileExtArr + @"\r\n"); } else { if (((int)upload.FileContent.Length) > (20 * 0x400)) { builder2.Append("照片" + upload.FileName + "大小超过20" + @"KB\r\n"); } else { str3 = DataSecurity.MakeFileRndName(); foldername = base.Request.PhysicalApplicationPath + (VirtualPathUtility.AppendTrailingSlash("/Uploadfiles/Source")).Replace("/", "\\");// + this.FileSavePath() filename = FileSystemObject.CreateFileFolder(foldername, HttpContext.Current) + str3 + str2; upload.SaveAs(filename); builder2.Append("照片" + upload.FileName + @"上传成功\r\n"); this.txtpic.Text = "UpLoadFiles/Source/" + str3 + str2; showphoto.Src = "../../UpLoadFiles/Source/" + str3 + str2; } } } //if (builder2.Length > 0) //{ // Response.Write("<script language=\"javascript\" type=\"text/javascript\">alert('" + builder2.ToString() + "');/script>"); // Page.Response.Redirect("Advertisement.aspx"); // this.txtpic.Text = "UpLoadFiles/Plus/" + str3 + str2; //} }
/// <summary> /// 保存上传课程包,获得保存文件名及物理路径 /// </summary> /// <param name="fudpackage"></param> /// <returns></returns> public static string PackageUpload(FileUpload fudpackage) { string msg = "信息"; string uploadfile=fudpackage.PostedFile.FileName; string saveFile = ""; if (uploadfile != "") { string fileName = uploadfile.Substring(uploadfile.LastIndexOf("\\") + 1); string fileType = fileName.Substring(fileName.LastIndexOf(".") + 1); if (fileType.ToLower() == "rar") { string savePath = CreateTempPath();//保存物理路径 saveFile = Checkbdir(savePath) + fileName;//保存文件名物理路径 fudpackage.SaveAs(saveFile);//按原文件名保存 LearnSite.Store.SharpZip.UnpackFiles(saveFile, savePath);//将上传的课程包解压到当前文件夹下 msg = "已解压成功,但导入失败!"; int newCid = ImportXml(savePath); //从当前文件夹读取 xml文件,将课程导入到数据库中(自动修改课程内容的链接地址) if (newCid != 0) //再创建新Cid文件夹,再课程包再解压到新Cid文件夹中。 { string newCidPath = HttpContext.Current.Server.MapPath(LearnSite.Store.CourseStore.CreateStore(newCid)); LearnSite.Store.SharpZip.UnpackFiles(saveFile, newCidPath);//将课程包重新解压到新课程目录下 DelOtherFiles(newCidPath);//递归调用自己,直接删除目录及子目录下后缀为asp|aspx|exe的非法文件 LearnSite.Store.XmlCourse.CourseToXml(newCid);//再在新建Cid文件夹中重建xml msg = "导入课程包成功!"; } else { msg = "课程包无内容,不能导入课程!"; } Directory.Delete(savePath, true);//最后删除临时文件夹 } else { msg = "课程包不是rar文件格式"; } } else { msg = "无上传课程包"; } return msg;//返回是否生成 }
public string img(FileUpload upload) { string str = ""; string filename = upload.FileName; string type = filename.Substring(filename.LastIndexOf(".") + 1).ToLower(); if (type == "jpg" || type == "bmp" || type == "gif" || type == "png") { str = "/public/user_img/" + DateTime.Now.ToString("yyyyMMddmmhhss") + "." + type; if (!File.Exists(filename)) { upload.SaveAs(MapPath(str)); } else { MessShowBox.show("文件已存在,请重命名后再上传", this); } } return str; }
public void AddImage(ref Image_Data imageData,string userLoginName, string albumName, FileUpload imageUrlFU) { //加入新的图片,包括数据库,根据给出的userLoginName和albumName计算路径 imageData.imageUrl = BASE_PATH + "\\" + USER_FILE_PREFIX + userLoginName + "\\" + ALBUM_FILE_PREFIX + albumName + "\\" + IMAGE_PREFIX + imageData.imageName; if (imageUrlFU.FileName.Length > 0) { string exname = imageUrlFU.FileName.Split('.')[1]; if (exname.ToLower() == "jpg" || exname.ToLower() == "gif" || exname.ToLower() == "png") { imageData.imageUrl += "." + exname; imageUrlFU.SaveAs(MAP_PATH + "\\" + imageData.imageUrl); } } mImageDB.InsertImage(ref imageData); }
//注意: FineUIMvc 中使用 fileUpload 必须使用 asp.net 原带控件 而且PageManage 中 EnableAjax 设置为 false static public string fileUpload(System.Web.UI.WebControls.FileUpload fUpload, string sPath) { string sFileName = ""; if (fUpload.HasFile) { //文件名:精确到毫秒 sFileName = DateTime.Now.ToString("yyyymmddhhmmssfff") + System.IO.Path.GetExtension(fUpload.FileName); //上传文件 try { fUpload.SaveAs(System.Web.HttpContext.Current.Server.MapPath(sPath + sFileName)); } catch (Exception e) { FineUIMvc.Alert.ShowInParent("文件上传失败,请检查数据!<br>出错信息:" + e.Message, FineUIMvc.MessageBoxIcon.Error); } } return(sFileName); }
public static bool UploadImage(FileUpload ful, string root, string folderContain, ref string url) { bool ret = false; DateTime dt = DateTime.Now; string fileName = dt.Year.ToString() + dt.Month.ToString() + dt.Day.ToString() + dt.Hour.ToString() + dt.Minute.ToString() + dt.Second.ToString() + dt.Millisecond.ToString(); url = folderContain + fileName + Path.GetExtension(ful.FileName); try { ful.SaveAs(root + url); ret = true; } catch { ret = false; } //TODO: Upload image lên folderContain return ret; }
public void AddAlbum(ref Album_Data albumData, string userLoginName,FileUpload albumLogoFU) { //创建相册并且创建相册目录 CreateAlbumFile(MAP_PATH+"\\"+BASE_PATH+"\\"+USER_FILE_PREFIX+userLoginName+"\\"+ALBUM_FILE_PREFIX+albumData.albumName); albumData.logoUrl = BASE_PATH + "\\" + USER_FILE_PREFIX + userLoginName + "\\" + ALBUM_FILE_PREFIX + albumData.albumName + "\\" + ALBUM_LOGO_PREFIX + albumData.albumName; string exname; if (albumLogoFU.FileName.Length > 0) { exname = albumLogoFU.FileName.Split('.')[1]; if (exname.ToLower() == "jpg" || exname.ToLower() == "gif" || exname.ToLower() == "png") { albumData.logoUrl += "." + exname; albumLogoFU.SaveAs(MAP_PATH+"\\"+albumData.logoUrl); } } mAlbumDB.InsertAlbum(ref albumData); }
private string UpLoadImage(System.Web.UI.WebControls.FileUpload uploadfileControl) { if (!uploadfileControl.HasFile) { throw new Exception("No file exist."); } string strInputFile = Server.MapPath(".") + "\\UploadedImages\\original"; if (!System.IO.Directory.Exists(strInputFile)) { System.IO.Directory.CreateDirectory(strInputFile); } DateTime now = DateTime.Now; string strData = now.ToString("yyyyMMdd_HHmmss_") + now.Millisecond + "_" + (new Random().Next() % 1000).ToString(); strInputFile = strInputFile + "\\" + strData + uploadfileControl.FileName; uploadfileControl.SaveAs(strInputFile); return(strInputFile); }
//Upload file to file path defined in web.config public string Upload(FileUpload fileUpload) { string newFileName = ""; if (IsFileValid(fileUpload)) { newFileName = GenerateNewFileName() + ".pdf"; try { fileUpload.SaveAs(System.Web.HttpContext.Current.Server.MapPath(destinationPath) + newFileName); } catch (Exception ex) { throw new Exception("The file upload path is not available : " + ex.Message); } } return newFileName; }
/// <summary> /// 保存资源上传文件 /// </summary> /// <param name="FUsoft"></param> /// <returns></returns> public static string Fupload(FileUpload FUsoft) { string uploadfile = FUsoft.PostedFile.FileName; string myfile = ""; if (uploadfile != "") { string filename = uploadfile.Substring(uploadfile.LastIndexOf("\\") + 1); string DownloadPath = "~/Download/"; string realpath = HttpContext.Current.Server.MapPath(DownloadPath); string NowTime = DateTime.Now.ToShortDateString(); string Creatfile = NowTime + filename; if (!Directory.Exists(realpath)) { Directory.CreateDirectory(realpath); } FUsoft.SaveAs(Checkbdir(realpath) + Creatfile); myfile = Checkpdir(DownloadPath) + Creatfile; } return myfile; }
/// <summary> /// �ϴ��ļ� /// </summary> /// <param name="fileUpload">�ϴ��ؼ�</param> /// <param name="upPath">�ϴ�Ŀ¼</param> public void SaveAs(FileUpload fileUpload, out string upPath) { if (fileUpload == null) { throw new ArgumentNullException("fileUpload"); } upPath = string.Empty; try { int size = fileUpload.PostedFile.ContentLength; //�ж��ļ���С if (size > _fileSize) { _message = "�ļ�̫�����ϴ���"; } else { upPath = _filePath + DateTime.Now.ToShortDateString(); //�ж�Ŀ¼�Ƿ���ڣ������ڴ���Ŀ¼ if (!Directory.Exists(HttpContext.Current.Server.MapPath(upPath))) { Directory.CreateDirectory(HttpContext.Current.Server.MapPath(upPath)); } string filename = string.Concat(upPath, @"/", fileUpload.FileName); upPath = filename; //�ϴ��ļ� fileUpload.SaveAs(HttpContext.Current.Server.MapPath(filename)); } } catch (Exception ex) { _message = "�ļ��ϴ�ʧ��:" + ex.Message; throw; } }
public string fl_up(System.Web.UI.WebControls.FileUpload f1, string lj) { string str = ""; if (f1.HasFile) { string tp = f1.PostedFile.FileName.Substring(f1.PostedFile.FileName.LastIndexOf(".")); string fileContentType = tp.ToLower(); if (fileContentType == ".jpg" || fileContentType == ".gif" || fileContentType == ".png") { string fileName = DateTime.Now.ToString("yyyyMMddhhmmssfff") + "B" + tp; // 文件名称 string webFilePath = lj + fileName; string fpts = lj; if (!System.IO.Directory.Exists(fpts)) //如果目录不存在,创建 { System.IO.Directory.CreateDirectory(fpts); } while (System.IO.File.Exists(webFilePath)) { Int64 llj = Convert.ToInt64(DateTime.Now.ToString("yyyyMMddhhmmssfff")) + 1; fileName = llj.ToString() + "B" + tp; webFilePath = fpts + fileName; } try { f1.SaveAs(webFilePath); // 使用 SaveAs 方法保存文件 str = fileName; } catch (Exception) { str = "0"; } } else { str = "1"; } } return(str); }
/** * Ver de mover este metodo a una clase base para que sea hereada por todas las paginas WEB que requieran de subida de fotos. * OPCIONAL - Parametrizar restricciones de tipo/tamaño */ private string UploadFile(FileUpload Archivo) { if (Archivo.HasFile) { try { if (Archivo.PostedFile.ContentType == "image/jpeg") { if (Foto.PostedFile.ContentLength < 1024000) { string filename = Guid.NewGuid().ToString("N"); Archivo.SaveAs(Server.MapPath("~/images/") + filename); return ResolveUrl("~/") + "images/" + filename; } else { throw new Exception("El archivo debe pesar menos de 1 mb!"); } } else { throw new Exception("Solo se aceptan archivos del tipo jpg!"); } } catch (Exception ex) { throw ex; } } else { throw new Exception("No se seleccionó ningún archivo!"); } }
/// <summary> /// 上传附件 /// </summary> /// <param name="FileUpload"></param> /// <param name="tableName"></param> /// <param name="Id"></param> /// <returns></returns> public static string SaveAnnex(System.Web.UI.WebControls.FileUpload FileUpload, string tableName, string Id) { if (((System.Web.UI.WebControls.FileUpload)FileUpload).HasFile) { //判断是否允许上传类型 string FileExt = System.IO.Path.GetExtension(FileUpload.FileName); FileExt = FileExt.ToLower(); if (FileExt.Length < 1) { return(""); } string FileType = System.Configuration.ConfigurationManager.AppSettings["FileType1"]; if (FileType.IndexOf(FileExt) == -1) { return(FileUpload.PostedFile.FileName + " 该文件类型不支持上传!"); } //判断文件大小是否可以上传 string strFileSize = System.Configuration.ConfigurationManager.AppSettings["FileSize1"]; int FileSize = FileUpload.PostedFile.ContentLength; if (FileSize > int.Parse(strFileSize)) { return("文件太大,不允许上传!"); } //计算出文件名 为时间的年月日时分秒+3位的随机数 Random rand = new Random(); DateTime time = new DateTime(); string filename = time.ToString("yyyyMMddHHmmss") + DateTime.Now.Millisecond.ToString() + rand.Next(999).ToString() + FileUpload.ID.Substring(4, 1); //上传文件 string strpath = System.Configuration.ConfigurationManager.AppSettings["FileSavePath"] + DateTime.Now.ToString("yyyy") + "\\" + DateTime.Now.ToString("MM") + "\\" + filename + FileExt; FileUpload.SaveAs(strpath); } return(""); }
protected String fileUploadName(FileUpload fileupload, Label label) { try { if (fileupload.HasFile) { if (fileupload.PostedFile.ContentLength < General.IMAGE_SIZE) { string fileUploadDir = Server.MapPath(General.ADMIN_IMAGE_UPLOAD); if (!System.IO.Directory.Exists(fileUploadDir)) { System.IO.Directory.CreateDirectory(fileUploadDir); } fileupload.SaveAs(fileUploadDir + fileupload.PostedFile.FileName); label.Text = "File (<b>" + fileupload.FileName + "</b>) is saved!"; return fileupload.FileName; } else { label.Text = "Error: File upload has to be less than " + General.GetImageSize(General.IMAGE_SIZE) + "mbs !"; return null; } } else { label.Text = "Error: You have not specified a file!"; return null; } } catch (Exception ex) { label.Text = "Error: " + ex.Message.ToString(); return null; } }
/// <summary> /// 文件上传(asp:FileUpload的对象myControl,服务器地址severUrl) /// </summary> /// <param name="myControl"></param> /// <param name="severUrl"></param> /// <returns></returns> public bool SaveImg(System.Web.UI.WebControls.FileUpload myControl, string severUrl) { //获取文件的后缀名picLastName string localUrl = myControl.PostedFile.FileName;//获取上传的文件路径(本地路径) int index = localUrl.LastIndexOf("."); string picLastName = localUrl.Substring(index); if (picLastName != ".jpeg" && picLastName != ".jpg" && picLastName != ".gif" && picLastName != ".png" && picLastName != ".bmp") { Response.Write("<script language='javascript'>alert('图片格式不正确!')</script>"); return(false); } int size = myControl.PostedFile.ContentLength; if (size > (1024 * 1024) || size < 1) { Response.Write("<script language='javascript'>alert('图片大小必须在1MB以内!')</script>"); return(false); } //上传后的文件名 ; //根据上传时间给文件命名 pictureName = DateTime.Now.ToString("yyyyMMddhhmmss") + picLastName; try { myControl.SaveAs(severUrl + "/" + pictureName); return(true); } catch (Exception ex) { Response.Write("<script language='javascript'>alert('图片上传失败')</script>"); return(false); } }
public static string SaveFile(System.Web.UI.WebControls.FileUpload fuImagen, int year, string path) { // Obtener el nombre del archivo que desea cargar. string archivo = fuImagen.FileName; String url = path + archivo; /*Se obtiene la extensión del archivo*/ FileInfo fi = new FileInfo(url); string ext = fi.Extension; /*Se obtiene el nombre y la extrensión del archivo*/ String[] substrings = fi.Name.Split('.'); // Path del directorio donde vamos a guardar el archivo string pathToCheck = path + year; //Verificamos si existe el directorio, sino existe se crea if (!Directory.Exists(pathToCheck)) { Directory.CreateDirectory(pathToCheck); } // Crear la ruta y el nombre del archivo para comprobar si hay duplicados. pathToCheck = pathToCheck + "\\" + substrings[0] + ext; // Compruebe si ya existe un archivo con el // mismo nombre que el archivo que desea cargar . if ((System.IO.File.Exists(pathToCheck))) { return(pathToCheck); //El archivo existe } else { // Llame al método SaveAs para guardar el archivo // guardado en el directorio especificado. fuImagen.SaveAs(pathToCheck); return(pathToCheck); } }
/// <summary> /// 上传文件(默认文件名) /// </summary> /// <param name="fileUploadControl">上传控件ID</param> /// <param name="SavePath">指定目录</param> /// <param name="IsTimeName">启用时间重命名</param> /// <returns></returns> public bool UploadFile(FileUpload fileUploadControl, string SavePath, bool IsTimeName) { string filename = fileUploadControl.FileName; if (IsTimeName) { //时间+扩展名 filename = DateTime.Now.Ticks.ToString() + filename.Substring(filename.LastIndexOf(".")); } try { string FileInServerName = BaseOp.WebPathTran(SavePath) + filename; fileUploadControl.SaveAs(FileInServerName); return true; } catch (Exception ex) { throw ex; return false; } }
public static bool Upload(FileUpload control,out string ImageUrl,out string ImageShortUrl,out string Message) { string RootPath = Config.RootPath; bool Result = false; ImageUrl = String.Empty; ImageShortUrl = String.Empty; Message = String.Empty; if (control.HasFile) { //用日期作为分割子文件夹的依据,防止文件在同一个文件夹下堆积过多导致IO效率降低 string RelativePath = DateTime.Today.ToString("yyyy-MM") + "\\"; string FileExtension = Path.GetExtension(control.FileName).ToLower(); string FileName = Guid.NewGuid().ToString() + FileExtension; if (control.PostedFile.ContentLength <= Config.MaxSize && Config.AllowedFormat.Contains(FileExtension.Substring(1))) { if (!Directory.Exists(RootPath + RelativePath)) Directory.CreateDirectory(RootPath + RelativePath); control.SaveAs(RootPath + RelativePath + FileName); ImageUrl = (Config.RootUrl + RelativePath + FileName).Replace("\\","/"); ImageShortUrl = ImageUrl.Replace(Config.UrlPrefix,String.Empty); Result = true; } else { Message = String.Format("只允许上传{0}格式的图片,且大小不可超过{1}kb",Config.AllowedFormat,Config.MaxSize/1024); } } else { Message = "上传文件不能为空"; } return Result; }
protected void btnFileUpload_Click(object sender, EventArgs e) { string id = string.Format("Id: {0} Uri: {1}", Guid.NewGuid(), HttpContext.Current.Request.Url); using (Utils utility = new Utils()) { utility.MethodStart(id, System.Reflection.MethodBase.GetCurrentMethod()); } try { this._saveOperation = new SaveOperation(); this._editOperation = new EditOperation(); this._nf3Template = new Bill_Sys_NF3_Template(); string physicalPath = this._nf3Template.getPhysicalPath(); for (int i = 0; i < this.grdDocumentGrid.Items.Count; i++) { System.Web.UI.WebControls.FileUpload fileUpload = (System.Web.UI.WebControls.FileUpload) this.grdDocumentGrid.Items[i].FindControl("fileuploadDocument"); string str = ""; if (fileUpload.FileName != "") { Bill_Sys_RequiredDocumentBO billSysRequiredDocumentBO = new Bill_Sys_RequiredDocumentBO(); string nodePath = billSysRequiredDocumentBO.GetNodePath(this.grdDocumentGrid.Items[i].Cells[this.COL_I_NODE_TYPE_ID].Text, this.txtCaseID.Text, ((Bill_Sys_BillingCompanyObject)this.Session["BILLING_COMPANY_OBJECT"]).SZ_COMPANY_ID); nodePath = nodePath.Replace("\\", "/"); str = string.Concat(physicalPath, nodePath); if (!Directory.Exists(str)) { Directory.CreateDirectory(str); } fileUpload.SaveAs(string.Concat(str, "/", fileUpload.FileName)); ArrayList arrayLists = new ArrayList(); arrayLists.Add(this.txtCaseID.Text); arrayLists.Add(this.grdDocumentGrid.Items[i].Cells[18].Text.Replace("/", "")); arrayLists.Add(((Bill_Sys_BillingCompanyObject)this.Session["BILLING_COMPANY_OBJECT"]).SZ_COMPANY_ID); arrayLists.Add(fileUpload.FileName); arrayLists.Add(string.Concat(nodePath, "/")); arrayLists.Add(((Bill_Sys_UserObject)this.Session["USER_OBJECT"]).SZ_USER_NAME); arrayLists.Add(this.grdDocumentGrid.Items[i].Cells[this.COL_I_NODE_TYPE_ID].Text.ToString()); string str1 = this._nf3Template.SaveDocumentData(arrayLists); if (!(this.grdDocumentGrid.Items[i].Cells[1].Text != "") || !(this.grdDocumentGrid.Items[i].Cells[1].Text != " ")) { this.txtDocID.Text = this.grdDocumentGrid.Items[i].Cells[this.COL_I_DOCUMENT_TYPE_ID].Text; if (!(this.grdDocumentGrid.Items[i].Cells[8].Text != "") || !(this.grdDocumentGrid.Items[i].Cells[8].Text != " ")) { this.txtAssignOn.Text = ""; } else { this.txtAssignOn.Text = this.grdDocumentGrid.Items[i].Cells[8].Text; } ExtendedDropDownList.ExtendedDropDownList extendedDropDownList = (ExtendedDropDownList.ExtendedDropDownList) this.grdDocumentGrid.Items[i].FindControl("extddlAssignTo"); if (!(extendedDropDownList.Text != "NA") || !(extendedDropDownList.Text != "")) { this.txtAssignTo.Text = ""; } else { this.txtAssignTo.Text = extendedDropDownList.Text; } TextBox textBox = (TextBox)this.grdDocumentGrid.Items[i].FindControl("txtNotes"); if (textBox.Text == "") { this.txtNotes.Text = ""; } else { this.txtNotes.Text = textBox.Text; } this.txtRecieved.Text = "1"; this.txtImageId.Text = str1; this._saveOperation.WebPage = this.Page; this._saveOperation.Xml_File = "CaseTypeDocumentXML.xml"; this._saveOperation.SaveMethod(); } else { this.txtDocID.Text = this.grdDocumentGrid.Items[i].Cells[1].Text; if (!(this.grdDocumentGrid.Items[i].Cells[8].Text != "") || !(this.grdDocumentGrid.Items[i].Cells[8].Text != " ")) { this.txtAssignOn.Text = ""; } else { this.txtAssignOn.Text = this.grdDocumentGrid.Items[i].Cells[8].Text; } ExtendedDropDownList.ExtendedDropDownList extendedDropDownList1 = (ExtendedDropDownList.ExtendedDropDownList) this.grdDocumentGrid.Items[i].FindControl("extddlAssignTo"); if (!(extendedDropDownList1.Text != "NA") || !(extendedDropDownList1.Text != "")) { this.txtAssignTo.Text = ""; } else { this.txtAssignTo.Text = extendedDropDownList1.Text; } TextBox textBox1 = (TextBox)this.grdDocumentGrid.Items[i].FindControl("txtNotes"); if (textBox1.Text == "") { this.txtNotes.Text = ""; } else { this.txtNotes.Text = textBox1.Text; } this.txtRecieved.Text = "1"; this.txtImageId.Text = str1; this._editOperation.WebPage = this.Page; this._editOperation.Xml_File = "CaseTypeDocumentXML.xml"; this._editOperation.Primary_Value = this.grdDocumentGrid.Items[i].Cells[1].Text; this._editOperation.UpdateMethod(); } } } this.BindCaseDocumentGrid(); this.usrMessage.PutMessage("Changes to the server were made successfully"); this.usrMessage.SetMessageType(UserControl_ErrorMessageControl.DisplayType.Type_UserMessage); this.usrMessage.Show(); } catch (Exception ex) { Elmah.ErrorSignal.FromCurrentContext().Raise(ex); using (Utils utility = new Utils()) { utility.MethodEnd(id, System.Reflection.MethodBase.GetCurrentMethod()); } string str2 = "Error Request=" + id + ".Please share with Technical support."; base.Response.Redirect("Bill_Sys_ErrorPage.aspx?ErrMsg=" + str2); } //Method End using (Utils utility = new Utils()) { utility.MethodEnd(id, System.Reflection.MethodBase.GetCurrentMethod()); } }
void btn_Click(object sender, EventArgs e) { Button btn = sender as Button; try { BP.Web.Controls.DDL DDL_ImpWay = (BP.Web.Controls.DDL) this.Pub1.FindControl("DDL_ImpWay"); System.Web.UI.WebControls.FileUpload fuit = (System.Web.UI.WebControls.FileUpload) this.Pub1.FindControl("fup"); if (DDL_ImpWay.SelectedIndex == 0) { this.Alert("请选择导入方式."); return; } string tempPath = this.Request.PhysicalApplicationPath + "\\Temp\\"; if (System.IO.Directory.Exists(tempPath) == false) { System.IO.Directory.CreateDirectory(tempPath); } MapDtl dtl = new MapDtl(this.FK_MapDtl); //求出扩展名. string fileName = fuit.FileName.ToLower(); if (fileName.Contains(".xls") == false) { this.Alert("上传的文件必须是excel文件."); return; } string ext = ".xls"; if (fileName.Contains(".xlsx")) { ext = ".xlsx"; } //保存临时文件. string file = tempPath + WebUser.No + ext; fuit.SaveAs(file); GEDtls dtls = new GEDtls(this.FK_MapDtl); System.Data.DataTable dt = BP.DA.DBLoad.GetTableByExt(file); file = this.Request.PhysicalApplicationPath + "\\DataUser\\DtlTemplete\\" + this.FK_MapDtl + ext; if (System.IO.File.Exists(file) == false) { if (ext == ".xlsx") { file = this.Request.PhysicalApplicationPath + "\\DataUser\\DtlTemplete\\" + this.FK_MapDtl + ".xls"; } else { file = this.Request.PhysicalApplicationPath + "\\DataUser\\DtlTemplete\\" + this.FK_MapDtl + ".xls"; } } System.Data.DataTable dtTemplete = BP.DA.DBLoad.GetTableByExt(file); #region 检查两个文件是否一致。 foreach (DataColumn dc in dtTemplete.Columns) { bool isHave = false; foreach (DataColumn mydc in dt.Columns) { if (dc.ColumnName == mydc.ColumnName) { isHave = true; break; } } if (isHave == false) { throw new Exception("@您导入的excel文件不符合系统要求的格式,请下载模版文件重新填入。"); } } #endregion 检查两个文件是否一致。 #region 生成要导入的属性. BP.En.Attrs attrs = dtls.GetNewEntity.EnMap.Attrs; BP.En.Attrs attrsExp = new BP.En.Attrs(); foreach (DataColumn dc in dtTemplete.Columns) { foreach (Attr attr in attrs) { if (attr.UIVisible == false) { continue; } if (attr.IsRefAttr) { continue; } if (attr.Desc == dc.ColumnName.Trim()) { attrsExp.Add(attr); break; } } } #endregion 生成要导入的属性. #region 执行导入数据. if (DDL_ImpWay.SelectedIndex == 1) { BP.DA.DBAccess.RunSQL("DELETE FROM " + dtl.PTable + " WHERE RefPK='" + this.WorkID + "'"); } int i = 0; Int64 oid = BP.DA.DBAccess.GenerOID("Dtl", dt.Rows.Count); string rdt = BP.DA.DataType.CurrentData; string errMsg = ""; foreach (DataRow dr in dt.Rows) { GEDtl dtlEn = dtls.GetNewEntity as GEDtl; dtlEn.ResetDefaultVal(); foreach (BP.En.Attr attr in attrsExp) { if (attr.UIVisible == false || dr[attr.Desc] == DBNull.Value) { continue; } string val = dr[attr.Desc].ToString(); if (val == null) { continue; } val = val.Trim(); switch (attr.MyFieldType) { case FieldType.Enum: case FieldType.PKEnum: SysEnums ses = new SysEnums(attr.UIBindKey); bool isHavel = false; foreach (SysEnum se in ses) { if (val == se.Lab) { val = se.IntKey.ToString(); isHavel = true; break; } } if (isHavel == false) { errMsg += "@数据格式不规范,第(" + i + ")行,列(" + attr.Desc + "),数据(" + val + ")不符合格式,改值没有在枚举列表里."; val = attr.DefaultVal.ToString(); } break; case FieldType.FK: case FieldType.PKFK: Entities ens = null; if (attr.UIBindKey.Contains(".")) { ens = BP.En.ClassFactory.GetEns(attr.UIBindKey); } else { ens = new GENoNames(attr.UIBindKey, "desc"); } ens.RetrieveAll(); bool isHavelIt = false; foreach (Entity en in ens) { if (val == en.GetValStrByKey("Name")) { val = en.GetValStrByKey("No"); isHavelIt = true; break; } } if (isHavelIt == false) { errMsg += "@数据格式不规范,第(" + i + ")行,列(" + attr.Desc + "),数据(" + val + ")不符合格式,改值没有在外键数据列表里."; } break; default: break; } if (attr.MyDataType == BP.DA.DataType.AppBoolean) { if (val.Trim() == "是" || val.Trim().ToLower() == "yes") { val = "1"; } if (val.Trim() == "否" || val.Trim().ToLower() == "no") { val = "0"; } } dtlEn.SetValByKey(attr.Key, val); } dtlEn.RefPKInt = (int)this.WorkID; dtlEn.SetValByKey("RDT", rdt); dtlEn.SetValByKey("Rec", WebUser.No); i++; dtlEn.InsertAsOID(oid); oid++; } #endregion 执行导入数据. if (string.IsNullOrEmpty(errMsg) == true) { this.Alert("共有(" + i + ")条数据导入成功。"); } else { this.Alert("共有(" + i + ")条数据导入成功,但是出现如下错误:" + errMsg); } } catch (Exception ex) { string msg = ex.Message.Replace("'", "‘"); this.Alert(msg); } }
public static bool resimKaydet2(this System.Web.UI.WebControls.FileUpload fileupload, string yol, out string resim, out string mesaj) { mesaj = ""; resim = yol; if (fileupload.HasFile) { string tamponresim = fileupload.FileName.ToLower(); if (!tamponresim.EndsWith("jpeg") && !tamponresim.EndsWith("gif") && !tamponresim.EndsWith("png") && !tamponresim.EndsWith("image/pjpeg") && !tamponresim.EndsWith("jpg")) { mesaj = "jpeg, jpg , png, gif formatlarından birini seçiniz..."; return(false); } try { string resimurl = ClassBLL.ZamanaGoreResimAdiGetir(); string[] kelimeler = tamponresim.Split(new string[] { "." }, StringSplitOptions.RemoveEmptyEntries); string uzanti = kelimeler[kelimeler.Length - 1]; //resimurl += "." + uzanti; string buyukresim = resimurl + "_buyuk." + uzanti; string kucukresim = resimurl + "_kucuk." + uzanti; string ortaresim = resimurl + "." + uzanti; resim += "/" + ortaresim; string buyukresimyol = System.Web.HttpContext.Current.Server.MapPath(yol) + "\\" + buyukresim; string kucukresimyol = System.Web.HttpContext.Current.Server.MapPath(yol) + "\\" + kucukresim; string ortaresimyol = System.Web.HttpContext.Current.Server.MapPath(yol) + "\\" + ortaresim; fileupload.SaveAs(buyukresimyol); // buyuk resim kaydediliyor //fileupload.SaveAs(kucukresimyol); // buyuk resim kaydediliyor //fileupload.SaveAs(ortaresimyol); // buyuk resim kaydediliyor ImageFormat imgformat = uzanti.resimFormati(); bool sonuc = ResimBoyutlandir(buyukresimyol, ortaresimyol, 256, imgformat); // orta resim kaydediliyor if (!sonuc) { return(sonuc); } sonuc = ResimBoyutlandir(buyukresimyol, kucukresimyol, 56, imgformat); // kucuk resim kaydediliyor if (!sonuc) { return(sonuc); } return(true); } catch (Exception exc) { mesaj = exc.Message; } return(false); } return(false); }
protected void BtnUpload_Click(object sender, EventArgs e) { this.m_FileExtArr = this.ViewState["FileExtArr"].ToString(); this.m_MaxFileSize = DataConverter.CLng(this.ViewState["MaxFileSize"].ToString()); if (!SiteConfig.SiteOption.EnableUploadFiles) { this.ReturnManage("本站不允许上传文件!"); } else { if (string.IsNullOrEmpty(this.m_FileExtArr)) { this.ReturnManage("要上传文件的字段没有指定上传文件类型"); } else { int num = DataConverter.CLng(base.Request.Form["ThumbIndex"]); string id = this.ViewState["FieldName"].ToString(); string thumbid = this.ViewState["ThumbField"].ToString(); StringBuilder builder = new StringBuilder(); builder.Append("<script language=\"javascript\" type=\"text/javascript\">"); int num2 = 0; StringBuilder builder2 = new StringBuilder(); for (int i = 0; i < 10; i++) { num2++; System.Web.UI.WebControls.FileUpload upload = (System.Web.UI.WebControls.FileUpload) this.FindControl("FileUpload" + i.ToString()); if (upload.HasFile) { string str2 = Path.GetExtension(upload.FileName).ToLower(); if (!this.CheckFilePostfix(str2.Replace(".", ""))) { builder2.Append("文件" + upload.FileName + "不符合扩展名规则" + this.m_FileExtArr + @"\r\n"); } else { if (((int)upload.FileContent.Length) > (this.m_MaxFileSize * 0x400)) { builder2.Append("文件" + upload.FileName + "大小超过" + this.m_MaxFileSize + @"KB\r\n"); } else { string str3 = DataSecurity.MakeFileRndName() + i.ToString(); string foldername = base.Request.PhysicalApplicationPath + (VirtualPathUtility.AppendTrailingSlash(SiteConfig.SiteOption.UploadDir) + this.FileSavePath(upload.FileName)).Replace("/", "\\"); string filename = FileSystemObject.CreateFileFolder(foldername, HttpContext.Current) + str3 + str2; int sizes = (int)upload.FileContent.Length; upload.SaveAs(filename); string thumbnailPath = ""; thumbnailPath = this.m_ShowPath + str3 + str2; if (i == num) { builder.Append("parent.ChangeThumbField(\"" + thumbnailPath + "\",\"sel_" + id + "\",\"txt_" + id + "\",\"txt_" + thumbid + "\");"); } else { builder.Append("parent.DealwithPhotoUpload(\"" + thumbnailPath + "\",\"sel_" + id + "\",\"txt_" + id + "\");"); } builder2.Append("文件" + upload.FileName + @"上传成功\r\n"); } } } } if (builder2.Length > 0) { builder.Append("parent.DealwithUploadErrMessage(\"" + builder2.ToString() + "\");"); } builder.Append("</script>"); this.Page.ClientScript.RegisterStartupScript(base.GetType(), "UpdateParent", builder.ToString()); } } }