protected override void SaveAs(string uploadPath, string fileName, HttpPostedFile file) { file.SaveAs(uploadPath + fileName); ImageTools.MakeThumbnail(uploadPath + fileName, uploadPath + "T32X32_" + fileName, 0x20, 0x20, MakeThumbnailMode.HW, InterpolationMode.High, SmoothingMode.HighQuality); ImageTools.MakeThumbnail(uploadPath + fileName, uploadPath + "T130X130_" + fileName, 130, 130, MakeThumbnailMode.HW, InterpolationMode.High, SmoothingMode.HighQuality); ImageTools.MakeThumbnail(uploadPath + fileName, uploadPath + "T300X390_" + fileName, 300, 390, MakeThumbnailMode.Cut, InterpolationMode.High, SmoothingMode.HighQuality); }
/// <summary> /// 是否允许 /// </summary> public static bool IsAllowedExtension(HttpPostedFile oFile, FileExtension[] fileEx) { int fileLen = oFile.ContentLength; byte[] imgArray = new byte[fileLen]; oFile.InputStream.Read(imgArray, 0, fileLen); MemoryStream ms = new MemoryStream(imgArray); System.IO.BinaryReader br = new System.IO.BinaryReader(ms); string fileclass = ""; byte buffer; try { buffer = br.ReadByte(); fileclass = buffer.ToString(); buffer = br.ReadByte(); fileclass += buffer.ToString(); } catch { } br.Close(); ms.Close(); foreach (FileExtension fe in fileEx) { if (Int32.Parse(fileclass) == (int)fe) return true; } return false; }
/// <summary> /// �̸�Ƽ���� �����Ѵ�. /// </summary> /// <param name="model"></param> /// <param name="file"></param> /// <returns></returns> public static int InsertEmoticon(EmoticonModel model, HttpPostedFile file) { object description = model.Description != null ? (object)model.Description : DBNull.Value; SqlParameter[] param = { CreateInParam("@String", SqlDbType.VarChar,50, model.EmoticonString), CreateInParam("@Value", SqlDbType.VarChar,255, model.EmoticonValue), CreateInParam("@Description", SqlDbType.Text, Int32.MaxValue, description), CreateReturnValue() }; SqlCommand cmd = GetSpCommand("UBE_InsertEmoticon", param); try { RepositoryManager.GetInstance().SaveAs("Emoticon", file); cmd.ExecuteNonQuery(); int seqNo = (int)cmd.Parameters["@ReturnValue"].Value; return seqNo; } catch(Exception e) { throw new UmcDataException("UBE_InsertEmoticon ���ν��� ȣ���� ����",e); } finally { ReleaseCommand(cmd); } }
//temp public bool GenerateVersions(HttpPostedFile file, string leafDirectoryName, string origFileName) { Dictionary<string, string> versions = new Dictionary<string, string>(); //Define the version to generate versions.Add("_thumb", "width=100&height=100&crop=auto&format=jpg"); //Crop to square thumbnail versions.Add("_medium", "maxwidth=400&maxheight=400format=jpg"); //Fit inside 400x400 area, jpeg //Loop through each uploaded file foreach (string fileKey in HttpContext.Current.Request.Files.Keys) { if (file.ContentLength <= 0) continue; //Skip unused file controls. var uploadFolder = GetPhysicalPathForFile(file, leafDirectoryName); if (!Directory.Exists(uploadFolder)) Directory.CreateDirectory(uploadFolder); //Generate each version string[] spFiles = origFileName.Split('.'); foreach (string suffix in versions.Keys) { string appndFileName = spFiles[0] + suffix; string fileName = Path.Combine(uploadFolder, appndFileName); fileName = ImageBuilder.Current.Build(file, fileName, new ResizeSettings(versions[suffix]), false, true); } } return true; }
/// <summary> /// Gets the file bytes /// </summary> /// <param name="context">The context.</param> /// <param name="uploadedFile">The uploaded file.</param> /// <returns></returns> public virtual byte[] GetFileBytes( HttpContext context, HttpPostedFile uploadedFile ) { // NOTE: GetFileBytes can get overridden by a child class (ImageUploader.ashx.cs for example) var bytes = new byte[uploadedFile.ContentLength]; uploadedFile.InputStream.Read( bytes, 0, uploadedFile.ContentLength ); return bytes; }
public void Upload([DataBind("Document")] Document document, HttpPostedFile uploadedFile) { if (uploadedFile != null) { using (new SessionScope()) { long length = uploadedFile.InputStream.Length; Byte[] fileContent = new byte[length]; int offset = 0; while (offset < fileContent.Length) { offset += uploadedFile.InputStream.Read(fileContent, 0, (int)length - offset); } string fileName = uploadedFile.FileName; document.BinaryFile = new BinaryDocument {BinaryData = fileContent, MimeType = FindMimeType(fileName)}; document.FileSize = fileContent.Length; document.UploadedOn = DateTime.Now; document.FileName = uploadedFile.FileName; document.Uploader = (Member) Context.CurrentUser; document.SaveAndFlush(); Flash["filename"] = document.FileName; RedirectToAction("Thanks"); } } }
public void AddFileToSession(string controlId, string filename, HttpPostedFile fileUpload) { if (fileUpload == null) { throw new ArgumentNullException("fileUpload"); } else if (controlId == String.Empty) { throw new ArgumentNullException("controlId"); } HttpContext currentContext = null; if ((currentContext = GetCurrentContext()) != null) { var mode = currentContext.Session.Mode; if (mode != SessionStateMode.InProc) { #if NET4 throw new InvalidOperationException(Resources_NET4.SessionStateOutOfProcessNotSupported); #else throw new InvalidOperationException(Resources.SessionStateOutOfProcessNotSupported); #endif } currentContext.Session.Add(GetFullID(controlId), fileUpload); } }
internal void AddFile(string key, HttpPostedFile file) { this.ThrowIfMaxHttpCollectionKeysExceeded(); this._all = null; this._allKeys = null; base.BaseAdd(key, file); }
internal static string DescribePostedFile(HttpPostedFile file) { if (file.ContentLength == 0 && string.IsNullOrEmpty(file.FileName)) return "[empty]"; return string.Format("{0} ({1}, {2} bytes)", file.FileName, file.ContentType, file.ContentLength); }
public WikiFile CreateFile(string fileName, Guid listingVersionGuid, Guid vendorGuid, HttpPostedFile file, FileType fileType, List<UmbracoVersion> v, string dotNetVersion, bool mediumTrust) { // we have to convert to the uWiki UmbracoVersion :( List<UmbracoVersion> vers = new List<UmbracoVersion>(); foreach (var ver in v) { vers.Add(UmbracoVersion.AvailableVersions()[ver.Version]); } //Create the Wiki File var uWikiFile = WikiFile.Create(fileName, listingVersionGuid, vendorGuid, file, GetFileTypeAsString(fileType), vers); //return the IMediaFile //Convert to Deli Media file var MediaFile = GetFileById(uWikiFile.Id); // If upload is package, extract the package XML manifest and check the version number + type [LK:2016-06-12@CGRT16] if (fileType == FileType.package) { var minimumUmbracoVersion = GetMinimumUmbracoVersion(MediaFile); if (!string.IsNullOrWhiteSpace(minimumUmbracoVersion)) { MediaFile.Versions = new List<UmbracoVersion>() { new UmbracoVersion { Version = minimumUmbracoVersion } }; } } MediaFile.DotNetVersion = dotNetVersion; SaveOrUpdate(MediaFile); return MediaFile; }
public HttpPostedFileWrapper(HttpPostedFile httpPostedFile) { if (httpPostedFile == null) { throw new ArgumentNullException("httpPostedFile"); } _file = httpPostedFile; }
/// <summary> /// Unpacks to file. /// </summary> /// <param name="args">The arguments.</param> /// <param name="file">The file.</param> private static void UnpackToFile(UploadArgs args, HttpPostedFile file) { Assert.ArgumentNotNull(args, "args"); Assert.ArgumentNotNull(file, "file"); var filename = FileUtil.MapPath(TempFolder.GetFilename("temp.zip")); file.SaveAs(filename); using (var zipReader = new ZipReader(filename)) { foreach (var zipEntry in zipReader.Entries) { var str = FileUtil.MakePath(args.Folder, zipEntry.Name, '\\'); if (zipEntry.IsDirectory) { Directory.CreateDirectory(str); } else { if (!args.Overwrite) str = FileUtil.GetUniqueFilename(str); Directory.CreateDirectory(Path.GetDirectoryName(str)); lock (FileUtil.GetFileLock(str)) FileUtil.CreateFile(str, zipEntry.GetStream(), true); } } } }
public static byte[] CreateBllImage(HttpPostedFile loadImage) { var image = new byte[loadImage.ContentLength]; loadImage.InputStream.Read(image, 0, loadImage.ContentLength); loadImage.InputStream.Close(); return image; }
//上传图片方法 private void UpLoadImage(HttpPostedFile file) { string fileExt = Path.GetExtension(file.FileName); if (fileExt != ".jpg" && fileExt != ".png") { return; } string newFileName = Common.CommonTools.GetStreamMD5(file.InputStream) + fileExt;//Guid.NewGuid().ToString() + fileExt;//创建新的文件名 DateTime nowDate = DateTime.Now; string dir = string.Format("/{0}/{1}/", nowDate.Year, nowDate.Month); if (!Directory.Exists(dir)) { Directory.CreateDirectory(Path.GetDirectoryName(HttpContext.Current.Request.MapPath(dir))); } file.SaveAs(HttpContext.Current.Request.MapPath(dir + newFileName)); using (Image image = Image.FromStream(file.InputStream)) { HttpContext.Current.Response.Write("success," + dir + newFileName + "," + image.Width + "," + image.Height); //var obj = new //{ // ReturnCode = "success", // ImagePath = dir + newFileName, // Width = image.Width, // Height = image.Height //}; //JavaScriptSerializer js = new JavaScriptSerializer(); //HttpContext.Current.Response.Write(js.Serialize(obj)); } }
/// <summary> /// /// </summary> /// <param name="httpPostedFile">待传输文件</param> /// <param name="orderId"></param> /// <param name="imageType">图片类型</param> /// <returns></returns> public ImgInfo UploadFile(HttpPostedFile httpPostedFile, string uploadType, UploadFrom uploadFrom) { ImgInfo imgInfo = new ImgInfo(); var fileName = ETS.Util.ImageTools.GetFileName(Path.GetExtension(httpPostedFile.FileName)); imgInfo.FileName = fileName; imgInfo.OriginalName = httpPostedFile.FileName; int fileNameLastDot = fileName.LastIndexOf('.'); //原图 string rFileName = string.Format("{0}{1}", fileName.Substring(0, fileNameLastDot), Path.GetExtension(fileName)); imgInfo.OriginFileName = rFileName; string saveDbFilePath; string saveDir = ""; string basePath = Ets.Model.ParameterModel.Clienter.CustomerIconUploader.Instance.GetPhysicalPath(uploadFrom); string fullFileDir = ETS.Util.ImageTools.CreateDirectory(basePath, uploadType, out saveDbFilePath); imgInfo.FullFileDir = fullFileDir; imgInfo.SaveDbFilePath = saveDbFilePath; if (fullFileDir == "0") { imgInfo.FailRemark = "创建目录失败"; return imgInfo; } var fullFilePath = Path.Combine(fullFileDir, rFileName); httpPostedFile.SaveAs(fullFilePath); var picUrl = saveDbFilePath + fileName; imgInfo.RelativePath = EnumUtils.GetEnumDescription(uploadFrom) + picUrl; imgInfo.PicUrl = ImageCommon.ReceiptPicConvert(uploadFrom, picUrl); return imgInfo; }
public void SaveGroup(Group group, HttpPostedFile file, List<long> selectedGroupTypeIDs) { if (group.Description.Length > 2000) { _view.ShowMessage("Your description is " + group.Description.Length.ToString() + " characters long and can only be 2000 characters!"); } else { group.AccountID = _webContext.CurrentUser.AccountID; group.PageName = group.PageName.Replace(" ", "-"); if (group.GroupID == 0 && _groupRepository.CheckIfGroupPageNameExists(group.PageName)) { _view.ShowMessage("The page name you specified is already in use!"); } else { if (file.ContentLength > 0) { List<Int64> fileIDs = _fileService.UploadPhotos(1, _webContext.CurrentUser.AccountID, _webContext.Files, 2); //should only be one item uploaded! if (fileIDs.Count == 1) group.FileID = fileIDs[0]; } group.GroupID = _groupService.SaveGroup(group); _groupToGroupTypeRepository.SaveGroupTypesForGroup(selectedGroupTypeIDs, group.GroupID); _redirector.GoToGroupsViewGroup(group.PageName); } } }
void MemoryStreamSmall(HttpPostedFile hpFile, string name, string type, int Width, int Height) { Image img = Image.FromStream(hpFile.InputStream); Bitmap bit = new Bitmap(img); if (bit.Width > Width || bit.Height > Height) { int desiredHeight = bit.Height; int desiredWidth = bit.Width; double heightRatio = (double)desiredHeight / desiredWidth; double widthRatio = (double)desiredWidth / desiredHeight; if (heightRatio > 1) { Width = Convert.ToInt32(Height * widthRatio); } else { Height = Convert.ToInt32(Width * heightRatio); } bit = new Bitmap(bit, Width, Height);//图片缩放 } bit.Save(name.Substring(0, name.LastIndexOf('.')) + "A." + type, System.Drawing.Imaging.ImageFormat.Jpeg); }
/// <summary> /// Gets the file bytes. /// </summary> /// <param name="context">The context.</param> /// <param name="uploadedFile">The uploaded file.</param> /// <returns></returns> public override Stream GetFileContentStream( HttpContext context, HttpPostedFile uploadedFile ) { if ( uploadedFile.ContentType == "image/svg+xml" ) { return base.GetFileContentStream( context, uploadedFile ); } else { Bitmap bmp = new Bitmap( uploadedFile.InputStream ); // Check to see if we should flip the image. var exif = new EXIFextractor( ref bmp, "\n" ); if ( exif["Orientation"] != null ) { RotateFlipType flip = OrientationToFlipType( exif["Orientation"].ToString() ); // don't flip if orientation is correct if ( flip != RotateFlipType.RotateNoneFlipNone ) { bmp.RotateFlip( flip ); exif.setTag( 0x112, "1" ); // reset orientation tag } } if ( context.Request.QueryString["enableResize"] != null ) { Bitmap resizedBmp = RoughResize( bmp, 1024, 768 ); bmp = resizedBmp; } var stream = new MemoryStream(); bmp.Save( stream, ContentTypeToImageFormat( uploadedFile.ContentType ) ); return stream; } }
public static bool SaveProductMultiImage(int ProductID, string CategoryPath, HttpPostedFile OriginalFile, out string[] FileNames) { string FileSuffix = Path.GetExtension(OriginalFile.FileName).Substring(1); bool ProcessResult = false; FileNames = GetMultiImageName(ProductID, CategoryPath, FileSuffix); if (config.AllowedFormat.ToLower().Contains(FileSuffix.ToLower()) && config.MaxSize * 1024 >= OriginalFile.ContentLength) { ImageHelper ih = new ImageHelper(); ih.LoadImage(OriginalFile.InputStream); for (int i = 2; i >= 0; i--) { if (config.ImageTypes[i].Width > 0 && config.ImageTypes[i].Height > 0) { ih.ScaleImageByFixSize(config.ImageTypes[i].Width, config.ImageTypes[i].Height, true); } FileInfo tempFile = new FileInfo(config.PathRoot + FileNames[i].Replace("/", "\\")); if (!tempFile.Directory.Exists) tempFile.Directory.Create(); ih.SaveImage(tempFile.FullName); } ih.Dispose(); ProcessResult = true; } return ProcessResult; }
public override void ProcessFile(HttpPostedFile file) { ManualResetEvent e = HttpContext.Current.Items["SyncUploadStorageAdapter"] as ManualResetEvent; try { UploadedFile item = UploadStorageService.CreateFile4Storage(file.ContentType); item.FileName = Path.GetFileName(file.FileName); item.ContentLength = file.ContentLength; item.InputStream = file.InputStream; if (!string.IsNullOrEmpty(HttpContext.Current.Request.Form["sectionId"])) { Section section = Section.Load(new Guid(HttpContext.Current.Request.Form["sectionId"])); if (section != null) section.AddFile(item); } item.AcceptChanges(); HttpContext.Current.Items["fileId"] = item.ID; } finally { if (e != null) { Trace.WriteLine(string.Format("Signaling event for file in section {0}.", HttpContext.Current.Request.Form["sectionId"])); e.Set(); } } }
public static void uploadFileControl(HttpPostedFile hpf, string savePath, string FileType, out string OutPath) { OutPath = string.Empty; if (hpf != null) { if (!string.IsNullOrEmpty(hpf.ToString())) { try { string ext = System.IO.Path.GetExtension(hpf.FileName).ToLower(); if (!IsFileType(FileType, ext)) { return; } string filename = Guid.NewGuid().ToString("N", System.Globalization.CultureInfo.InvariantCulture) + ext;//文件重命名_userId_CourseID string pathStr = HttpContext.Current.Server.MapPath("/" + savePath); if (!System.IO.Directory.Exists(pathStr)) { System.IO.Directory.CreateDirectory(pathStr); } string path = "/" + savePath + "/" + filename; hpf.SaveAs(HttpContext.Current.Server.MapPath(path)); OutPath = path; } catch (Exception) { throw; } } } else { OutPath = string.Empty; } }
public FileInfo SaveAs(string repositoryDir, HttpPostedFile postedFile, string saveFilename) { // ������ ������ ���� ����� string folder = RepositoryDirectory + "/" + repositoryDir; if( !Directory.Exists( folder )) Directory.CreateDirectory( folder ); // {0} : Web.config �� ������ upload ���� // {1} : �� ���� // {2} : ���ϸ� string fileName; if (saveFilename == null) fileName = Path.GetFileName(postedFile.FileName); else fileName = saveFilename; string saveFullName = string.Format("{0}/{1}/{2}", RepositoryDirectory, repositoryDir, fileName ); postedFile.SaveAs(saveFullName); return new FileInfo( saveFullName ); }
/// <summary> /// 上传文件 /// </summary> /// <param name="file">文件流</param> /// <param name="Folder">文件夹名字</param> /// <param name="fileExt">允许上传的文件名后缀(小写),用‘,’分隔</param> /// <param name="filename">返回的文件名</param> /// <returns></returns> public bool MakeThumbFile(System.Web.HttpPostedFile file, string Folder, string fileExt, ref string filename) { string FileName = DateTime.Now.ToString("yyyyMMddHHmmss") + Common.Number(4, false); if (file.ContentLength > 0) { System.IO.FileInfo _file = new System.IO.FileInfo(file.FileName); string _fileExt = _file.Name.ToLower().Substring(_file.Name.LastIndexOf('.') + 1), _fileName = FileName + "." + _fileExt, _folder = "../UploadFile/" + Folder + "/"; string[] FileExt = fileExt.Split(','); if (!Common.ArrayIsContains(FileExt, _fileExt)) { return(false); } else { filename = _fileName; FileUtils.CreateFile(_folder); string filePath = _folder + _fileName; file.SaveAs(Common.getAbsolutePath(filePath)); return(true); } } else { return(false); } }
/// <summary> /// 上传文件 /// </summary> /// <param name="PostFile">FileUpLoad控件</param> /// <param name="UpLoadPath">传入文件保存路径,如:/UpLoadFile/excel/ 返回文件绝对路径,如:/UpLoadFile/excel/a.xls</param> /// <param name="FileFormat">文件后缀,如:.xls</param> /// <returns>文件名称,如a.xls</returns> public static string UploadFile(HttpPostedFile PostFile, ref string UpLoadPath) { try { UpLoadPath += DateTime.Now.Year + "/" + DateTime.Now.Month; string savepath = HttpContext.Current.Server.MapPath(UpLoadPath); if (!Directory.Exists(savepath)) { Directory.CreateDirectory(savepath); } string ext = Path.GetExtension(PostFile.FileName); string filename = CreateIDCode() + ext; if (UpLoadPath.IndexOf(ext) == -1) //判断 { savepath = savepath + filename; } PostFile.SaveAs(savepath); UpLoadPath += filename; return filename; } catch (Exception ex) { return ex.Message; } }
public override ImagePreviewDTO SaveAspect(HttpPostedFile file) { ImagePreviewDTO previewDTO = base.SaveAspect(file); string Folder_60X60 = string.Format("{0}\\60X60", this.FolderServerPath); string Folder_120X120 = string.Format("{0}\\120X120", this.FolderServerPath); if (!System.IO.Directory.Exists(Folder_60X60)) { System.IO.Directory.CreateDirectory(Folder_60X60); } if (!System.IO.Directory.Exists(Folder_120X120)) { System.IO.Directory.CreateDirectory(Folder_120X120); } string fileName_60X60 = string.Format(Folder_60X60 + "\\{0}", previewDTO.FileName); string fileName_120X120 = string.Format(Folder_120X120 + "\\{0}", previewDTO.FileName); string orignalFilePath = string.Format(this.OrignalImageServerPath + "\\{0}", previewDTO.FileName); //自己需要使用的尺寸 IWEHAVE.ERP.GAIA.WEBUtil.FileManage.MakeThumbnail(orignalFilePath, fileName_60X60, 60, 60, "AHW"); IWEHAVE.ERP.GAIA.WEBUtil.FileManage.MakeThumbnail(orignalFilePath, fileName_120X120, 120, 120, "AHW"); CompanyImagePreviewDTO companyPreviewDTO = new CompanyImagePreviewDTO(previewDTO); companyPreviewDTO.Image_60X60 = string.Format("{0}/60X60/{1}", this.FolderPath, previewDTO.FileName); companyPreviewDTO.Image_120X120 = string.Format("{0}/120X120/{1}", this.FolderPath, previewDTO.FileName); return companyPreviewDTO; }
public static bool SaveProductMainImage(int ProductID, HttpPostedFile OriginalFile, out string[] FileNames) { string FileSuffix = Path.GetExtension(OriginalFile.FileName).Substring(1); bool ProcessResult = false; FileNames = GetMainImageName(ProductID, FileSuffix); if (!Directory.Exists(config.PathRoot)) Directory.CreateDirectory(config.PathRoot); if (config.AllowedFormat.ToLower().Contains(FileSuffix.ToLower()) && config.MaxSize * 1024 >= OriginalFile.ContentLength) { ImageHelper ih = new ImageHelper(); ih.LoadImage(OriginalFile.InputStream); for (int i = 2; i >= 0; i--) { if (config.ImageSets[i].Width > 0 && config.ImageSets[i].Height > 0) { ih.ScaleImageByFixSize(config.ImageSets[i].Width, config.ImageSets[i].Height, true); } ih.SaveImage(config.PathRoot + FileNames[i]); } ih.Dispose(); //foreach (string FileName in FileNames) //{ // //缩小图片为设置尺寸注意图片尺寸与名称对应 // OriginalFile.SaveAs(config.PathRoot + FileName); //} ProcessResult = true; } return ProcessResult; }
public PostedFile(HttpPostedFile httpPostedFile) { _fileName = httpPostedFile.FileName; _stream = httpPostedFile.InputStream; _contentType = httpPostedFile.ContentType; _length = httpPostedFile.ContentLength; }
/// <summary> /// 根据文件的前2个字节进行判断文件类型 ---说明255216是jpg;7173是gif;6677是BMP,13780是PNG;7790是exe,8297是rar /// </summary> /// <param name="hpf"></param> /// <param name="code">文件的前2个字节转化出来的小数</param> /// <returns></returns> public bool CheckUploadByTwoByte(HttpPostedFile hpf, Int64 code) { System.IO.FileStream fs = new System.IO.FileStream(hpf.FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read); System.IO.BinaryReader r = new System.IO.BinaryReader(fs); string fileclass = ""; byte buffer; try { buffer = r.ReadByte(); fileclass = buffer.ToString(); buffer = r.ReadByte(); fileclass += buffer.ToString(); } catch { } r.Close(); fs.Close(); // //if (fileclass == code.ToString()) //{ // return true; //} //else //{ // return false; //} return (fileclass == code.ToString()); }
public string SavePhoto(HttpPostedFile imageFile) { var path = @"~/Images/users_pic"; var filename = string.Format("{0}/{1}", path, imageFile.FileName); imageFile.SaveAs(System.Web.Hosting.HostingEnvironment.MapPath(filename)); return filename; }
/// <summary> /// /// </summary> /// <param name="file">文件流</param> /// <param name="path">保存路径</param> /// <param name="filename">返回文件名称</param> public void saveFile(System.Web.HttpPostedFile file, string path, ref string filename) { filename = DateTime.Now.ToString("yyyyMMddHHmmss") + Common.Number(4, false); System.IO.FileInfo _file = new System.IO.FileInfo(file.FileName); string _fileExt = _file.Extension.ToLower(); filename = filename + _fileExt; FileUtils.CreateFile(path); file.SaveAs(Common.getAbsolutePath(path + filename)); }
private bool yeniVideoGonder() { if (CheckBoxList1.SelectedIndex == -1) { Debug.WriteLine("LÜTFEN LİSTEDEN BİR SEÇİM YAPINIZ"); return(false); } System.Web.HttpPostedFile VideoInput = FileUpload1.PostedFile; string conStr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString; using (SqlConnection con = new SqlConnection(conStr)) { using (SqlCommand cmd = new SqlCommand()) { con.Open(); cmd.Connection = con; using (BinaryReader br = new BinaryReader(VideoInput.InputStream)) { byte[] Inputbytes = br.ReadBytes((int)VideoInput.InputStream.Length); cmd.CommandText = "INSERT INTO Videos (name, content) values (@name, @content)"; cmd.Parameters.AddWithValue("@name", Path.GetFileName(VideoInput.FileName)); cmd.Parameters.AddWithValue("@content", Inputbytes); cmd.ExecuteNonQuery(); } } foreach (ListItem item in CheckBoxList1.Items) { if (item.Selected) { using (SqlCommand cmd = new SqlCommand()) { cmd.Connection = con; cmd.CommandText = "INSERT INTO usersVideos (Id,username, videoname) VALUES (@Id,@username, @videoname)"; cmd.Parameters.AddWithValue("@Id", item.Text + VideoInput.FileName); cmd.Parameters.AddWithValue("@username", item.Text); cmd.Parameters.AddWithValue("@videoname", VideoInput.FileName); cmd.ExecuteNonQuery(); } } } ///con.Close(); } ///Response.Redirect(Request.Url.AbsoluteUri); Debug.WriteLine("VİDEO BAŞARIYLA KAYDEDİLDİ"); return(true); }
protected void Page_Load(object sender, System.EventArgs e) { if (base.Request.QueryString["delimg"] != null) { string path = base.Server.HtmlEncode(base.Request.QueryString["delimg"]); path = base.Server.MapPath(path); if (System.IO.File.Exists(path)) { System.IO.File.Delete(path); } base.Response.Write("0"); base.Response.End(); } int num = int.Parse(base.Request.QueryString["imgurl"]); try { if (num < 1) { System.Web.HttpPostedFile httpPostedFile = base.Request.Files["Filedata"]; string str = System.DateTime.Now.ToString("yyyyMMddHHmmss_ffff", System.Globalization.DateTimeFormatInfo.InvariantInfo); string str2 = "/Storage/data/DistributorLogoPic/"; string text = str + System.IO.Path.GetExtension(httpPostedFile.FileName); httpPostedFile.SaveAs(Globals.MapPath(str2 + text)); try { System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(Globals.MapPath(str2 + text)); if (bitmap.Height > 200 || bitmap.Width > 200) { bitmap = DistributorLogoUpload.GetThumbnail(bitmap, 200, 200); } bitmap.Save(Globals.MapPath("/Utility/pics/headLogo.jpg"), System.Drawing.Imaging.ImageFormat.Jpeg); bitmap.Dispose(); } catch (System.Exception) { } base.Response.StatusCode = 200; base.Response.Write(str + "|/Storage/data/DistributorLogoPic/" + text); SiteSettings masterSettings = SettingsManager.GetMasterSettings(false); string path2 = masterSettings.DistributorLogoPic; path2 = base.Server.MapPath(path2); if (System.IO.File.Exists(path2)) { System.IO.File.Delete(path2); } masterSettings.DistributorLogoPic = "/Storage/data/DistributorLogoPic/" + text; SettingsManager.Save(masterSettings); } else { base.Response.Write("0"); } } catch (System.Exception) { base.Response.StatusCode = 500; base.Response.Write("服务器错误"); base.Response.End(); } finally { base.Response.End(); } }
public HttpResponseMessage UpdateCompany(CompanyModel _CompanyModel) { int iUploadedCnt = 0; try { bool conn = false; conn = db.Database.Exists(); if (!conn) { ConnectionTools.changeToLocalDB(db); conn = db.Database.Exists(); } if (conn) { // DEFINE THE PATH WHERE WE WANT TO SAVE THE FILES. string sPath = ""; sPath = System.Web.Hosting.HostingEnvironment.MapPath("~/Upload/"); System.Web.HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files; // CHECK THE FILE COUNT. for (int iCnt = 0; iCnt <= hfc.Count - 1; iCnt++) { System.Web.HttpPostedFile hpf = hfc[iCnt]; if (hpf.ContentLength > 0) { // CHECK IF THE SELECTED FILE(S) ALREADY EXISTS IN FOLDER. (AVOID DUPLICATE) if (!File.Exists(sPath + Path.GetFileName(hpf.FileName))) { // SAVE THE FILES IN THE FOLDER. hpf.SaveAs(sPath + Path.GetFileName(hpf.FileName)); iUploadedCnt = iUploadedCnt + 1; } } } if (_CompanyModel.COMPANY_ID != null && _CompanyModel.COMPANY_ID != 0) { var CompnyUp = (from a in db.TBL_COMPANY where a.COMAPNY_ID == _CompanyModel.COMPANY_ID select a).FirstOrDefault(); CompnyUp.COMPANY_NAME = _CompanyModel.NAME; CompnyUp.SHOPNAME = _CompanyModel.SHOPNAME; CompnyUp.PREFIX = _CompanyModel.PREFIX; CompnyUp.PREFIX_NUM = _CompanyModel.PREFIX_NUM; CompnyUp.TIN_NUMBER = _CompanyModel.TIN_NUMBER; CompnyUp.ADDRESS_1 = _CompanyModel.ADDRESS_1; CompnyUp.ADDRESS_2 = _CompanyModel.ADDRESS_2; CompnyUp.CITY = _CompanyModel.CITY; CompnyUp.STATE = _CompanyModel.STATE; CompnyUp.COUNTRY = _CompanyModel.COUNTRY; CompnyUp.PIN = _CompanyModel.PIN; CompnyUp.PHONE_NUMBER = _CompanyModel.PHONE_NUMBER; CompnyUp.MOBILE_NUMBER = _CompanyModel.MOBILE_NUMBER; CompnyUp.EMAIL = _CompanyModel.EMAIL; CompnyUp.WEBSITE = _CompanyModel.WEBSITE; CompnyUp.DEFAULT_TAX_RATE = _CompanyModel.DEFAULT_TAX_RATE; CompnyUp.IS_WARNED_FOR_NEGATIVE_STOCK = _CompanyModel.IS_WARNED_FOR_NEGATIVE_STOCK; CompnyUp.IS_WARNED_FOR_LESS_SALES_PRICE = _CompanyModel.IS_WARNED_FOR_LESS_SALES_PRICE; CompnyUp.TAX_PRINTED_DESCRIPTION = _CompanyModel.TAX_PRINTED_DESCRIPTION; CompnyUp.FIRST_DAY_OF_FINANCIAL_YEAR = _CompanyModel.FIRST_DAY_OF_FINANCIAL_YEAR; CompnyUp.FIRST_MONTH_OF_FINANCIAL_YEAR = _CompanyModel.FIRST_MONTH_OF_FINANCIAL_YEAR; CompnyUp.IMAGE_PATH = _CompanyModel.IMAGE_PATH; db.SaveChanges(); int ID = CompnyUp.COMAPNY_ID; if (_CompanyModel.BANK_ID != 0 && _CompanyModel.BANK_ID != null) { var BankUp = (from a in db.TBL_BANK where a.BANK_ID == _CompanyModel.BANK_ID select a).FirstOrDefault(); BankUp.ADDRESS_1 = _CompanyModel.BANK_ADDRESS_1; BankUp.ADDRESS_2 = _CompanyModel.BANK_ADDRESS_2; BankUp.BANK_NAME = _CompanyModel.BANK_NAME; BankUp.CITY = _CompanyModel.BANK_CITY; BankUp.COMPANY_ID = ID; BankUp.BANK_CODE = _CompanyModel.BANK_CODE; BankUp.PIN_CODE = _CompanyModel.BANK_PIN_CODE; BankUp.PHONE_NUMBER = _CompanyModel.BANK_PHONE_NUMBER; BankUp.STATE = _CompanyModel.BANK_STATE; db.SaveChanges(); long ba = BankUp.BANK_ID; if (_CompanyModel.BANK_ACCOUNT_ID != null && _CompanyModel.BANK_ACCOUNT_ID != 0) { var BankAcUp = (from a in db.TBL_BANK_ACCOUNT where a.BANK_ACCOUNT_ID == _CompanyModel.BANK_ACCOUNT_ID select a).FirstOrDefault(); BankAcUp.ACCOUNT_NUMBER = _CompanyModel.ACCOUNT_NUMBER; BankAcUp.BRANCH_NAME = _CompanyModel.BRANCH_NAME; BankAcUp.COMPANY_ID = ID; BankAcUp.BANK_ID = ba; BankAcUp.BRANCH_NAME = _CompanyModel.BRANCH_NAME; db.SaveChanges(); } } } return(Request.CreateResponse(HttpStatusCode.OK, "Ok")); } else { return(Request.CreateResponse(HttpStatusCode.ExpectationFailed)); } } catch (Exception ex) { throw; } finally { ConnectionTools.ChangeToRemoteDB(db); } }
public string UploadFile() { if (HttpContext.Current.Request.Files.AllKeys.Any()) { logger.Info("start Item Upload Exel File: "); var identity = User.Identity as ClaimsIdentity; int compid = 0, userid = 0; // Access claims foreach (Claim claim in identity.Claims) { if (claim.Type == "compid") { compid = int.Parse(claim.Value); } if (claim.Type == "userid") { userid = int.Parse(claim.Value); } } // Get the uploaded image from the Files collection System.Web.HttpPostedFile httpPostedFile = HttpContext.Current.Request.Files["file"]; if (httpPostedFile != null) { // Validate the uploaded image(optional) byte[] buffer = new byte[httpPostedFile.ContentLength]; using (BinaryReader br = new BinaryReader(httpPostedFile.InputStream)) { br.Read(buffer, 0, buffer.Length); } XSSFWorkbook hssfwb; // XSSFWorkbook workbook1; using (MemoryStream memStream = new MemoryStream()) { BinaryFormatter binForm = new BinaryFormatter(); memStream.Write(buffer, 0, buffer.Length); memStream.Seek(0, SeekOrigin.Begin); hssfwb = new XSSFWorkbook(memStream); string sSheetName = hssfwb.GetSheetName(0); ISheet sheet = hssfwb.GetSheet(sSheetName); AuthContext context = new AuthContext(); IRow rowData; ICell cellData = null; try { List <Customer> CustCollection = new List <Customer>(); for (int iRowIdx = 0; iRowIdx <= sheet.LastRowNum; iRowIdx++) { if (iRowIdx == 0) { } else { rowData = sheet.GetRow(iRowIdx); cellData = rowData.GetCell(0); rowData = sheet.GetRow(iRowIdx); if (rowData != null) { Customer cust = new Customer(); try { cust.CompanyId = 1; cellData = rowData.GetCell(1); col1 = cellData == null ? "" : cellData.ToString(); if (col1.Trim() == "" || col1 == null || col1 == "null") { break; } cust.Skcode = col1.Trim(); cellData = rowData.GetCell(2); col2 = cellData == null ? "" : cellData.ToString(); cust.ShopName = col2.Trim(); cellData = rowData.GetCell(3); col3 = cellData == null ? "" : cellData.ToString(); cust.Name = col3.Trim(); cellData = rowData.GetCell(4); col4 = cellData == null ? "" : cellData.ToString(); if (col4.Trim() == "" || col4 == null) { break; } cust.Mobile = col4.Trim(); cellData = rowData.GetCell(5); col5 = cellData == null ? "" : cellData.ToString(); cust.BillingAddress = col5.Trim(); cellData = rowData.GetCell(6); col6 = cellData == null ? "" : cellData.ToString(); cust.LandMark = col6.Trim(); cellData = rowData.GetCell(7); col7 = cellData == null ? "" : cellData.ToString(); Warehouse wh = context.Warehouses.Where(w => w.WarehouseName == col7.Trim()).FirstOrDefault(); if (wh != null) { cust.Warehouseid = wh.Warehouseid; cust.City = wh.CityName; cust.WarehouseName = wh.WarehouseName; } cellData = rowData.GetCell(8); col8 = cellData == null ? "" : cellData.ToString(); List <People> peoples = new List <People>(); try { peoples = context.Peoples.Where(x => x.DisplayName.Trim().ToLower() == col8.Trim().ToLower()).ToList(); if (peoples.Count != 0) { cust.ExecutiveId = peoples[0].PeopleID; } else { cust.ExecutiveId = 0; } } catch (Exception ex) { cust.ExecutiveId = 0; } cellData = rowData.GetCell(9); col9 = cellData == null ? "" : cellData.ToString(); if (col9.Trim() != "" && col9 != null) { cust.Emailid = col9.Trim(); } cellData = rowData.GetCell(10); col10 = cellData == null ? "" : cellData.ToString(); try { cust.ClusterId = Convert.ToInt32(col10.Trim()); } catch (Exception ex) { cust.ClusterId = 1; } cellData = rowData.GetCell(11); col11 = cellData == null ? "" : cellData.ToString(); if (col11.Trim() != "" && col11 != null) { cust.Day = col11.Trim(); } cellData = rowData.GetCell(12); col12 = cellData == null ? "" : cellData.ToString(); if (col12.Trim() == "" && col12 == null) { break; } cust.lat = Convert.ToDouble(col12.Trim()); cellData = rowData.GetCell(13); col13 = cellData == null ? "" : cellData.ToString(); if (col13.Trim() == "" && col13 == null) { break; } cust.lg = Convert.ToDouble(col13.Trim()); cellData = rowData.GetCell(14); col14 = cellData == null ? "" : cellData.ToString(); if (col14.Trim() != "" && col14 != null) { cust.BeatNumber = Convert.ToInt32(col14.Trim()); } cust.Active = true; cust.Password = "******"; cust.CompanyId = compid; CustCollection.Add(cust); } catch (Exception ex) { logger.Error("Error adding customer in collection " + "\n\n" + ex.Message + "\n\n" + ex.InnerException + "\n\n" + ex.StackTrace + cust.Name); } } } } context.AddBulkcustomer(CustCollection); } catch (Exception ex) { logger.Error("Error loading for \n\n" + ex.Message + "\n\n" + ex.InnerException + "\n\n" + ex.StackTrace); } } var FileUrl = Path.Combine(HttpContext.Current.Server.MapPath("~/UploadedFiles"), httpPostedFile.FileName); httpPostedFile.SaveAs(FileUrl); } } if (msgitemname != null) { return(msgitemname); } msg = "Your Exel data is succesfully saved"; return(msg); }
public string UploadFile() { if (HttpContext.Current.Request.Files.AllKeys.Any()) { logger.Info("start Item Upload Exel File: "); var identity = User.Identity as ClaimsIdentity; int compid = 0, userid = 0; // Access claims foreach (Claim claim in identity.Claims) { if (claim.Type == "compid") { compid = int.Parse(claim.Value); } if (claim.Type == "userid") { userid = int.Parse(claim.Value); } } // Get the uploaded image from the Files collection System.Web.HttpPostedFile httpPostedFile = HttpContext.Current.Request.Files["file"]; if (httpPostedFile != null) { // Validate the uploaded image(optional) byte[] buffer = new byte[httpPostedFile.ContentLength]; using (BinaryReader br = new BinaryReader(httpPostedFile.InputStream)) { br.Read(buffer, 0, buffer.Length); } XSSFWorkbook hssfwb; // XSSFWorkbook workbook1; using (MemoryStream memStream = new MemoryStream()) { BinaryFormatter binForm = new BinaryFormatter(); memStream.Write(buffer, 0, buffer.Length); memStream.Seek(0, SeekOrigin.Begin); hssfwb = new XSSFWorkbook(memStream); string sSheetName = hssfwb.GetSheetName(0); ISheet sheet = hssfwb.GetSheet(sSheetName); AuthContext context = new AuthContext(); IRow rowData; ICell cellData = null; try { List <Supplier> supCollection = new List <Supplier>(); for (int iRowIdx = 0; iRowIdx <= sheet.LastRowNum; iRowIdx++) { if (iRowIdx == 0) { } else { rowData = sheet.GetRow(iRowIdx); cellData = rowData.GetCell(0); rowData = sheet.GetRow(iRowIdx); if (rowData != null) { Category cat = null; SubCategory subcat = null; SubsubCategory subsubcat = new SubsubCategory(); BaseCategory basecat = null; try { // sup.CompanyId = 1; cellData = rowData.GetCell(0); col0 = cellData == null ? "" : cellData.ToString(); cat = context.Categorys.Where(x => x.CategoryName.ToLower().Equals(col0.ToLower())).FirstOrDefault(); if (cat == null) { cat = new Category(); cat.CategoryName = col0; cellData = rowData.GetCell(1); col1 = cellData == null ? "" : cellData.ToString(); cat.Code = col1; cat.CompanyId = compid; cat = context.AddCategory(cat); } cellData = rowData.GetCell(2); col2 = cellData == null ? "" : cellData.ToString(); subcat = context.SubCategorys.Where(x => x.SubcategoryName.ToLower().Equals(col2.ToLower()) && x.CategoryName.Equals(cat.CategoryName)).FirstOrDefault(); if (subcat == null) { subcat = new SubCategory(); subcat.CompanyId = compid; subcat.SubcategoryName = col2; subcat.CategoryName = cat.CategoryName; subcat.Categoryid = cat.Categoryid; subcat = context.AddSubCategory(subcat); } cellData = rowData.GetCell(3); col3 = cellData == null ? "" : cellData.ToString(); subsubcat = context.SubsubCategorys.Where(x => x.SubsubcategoryName.ToLower().Equals(col3.ToLower()) && x.CategoryName.Equals(x.CategoryName) && x.SubcategoryName.ToLower().Equals(subcat.SubcategoryName.ToLower())).FirstOrDefault(); if (subsubcat == null) { subsubcat = new SubsubCategory(); subsubcat.CompanyId = compid; subsubcat.SubsubcategoryName = col3; subsubcat.SubCategoryId = subcat.SubCategoryId; cellData = rowData.GetCell(4); col4 = cellData == null ? "" : cellData.ToString(); subsubcat.Code = col4; subsubcat.SubcategoryName = col2; subsubcat.CategoryName = cat.CategoryName; subsubcat.Categoryid = cat.Categoryid; subsubcat = context.AddSubsubCat(subsubcat); } cellData = rowData.GetCell(4); col4 = cellData == null ? "" : cellData.ToString(); basecat = context.BaseCategoryDb.Where(x => x.BaseCategoryName.ToLower().Equals(col4.ToLower())).FirstOrDefault(); if (basecat == null) { basecat = new BaseCategory(); basecat.CompanyId = compid; basecat.BaseCategoryName = col4; basecat = context.AddBaseCategory(basecat); } } catch (Exception ex) { logger.Error("Error adding customer in collection " + "\n\n" + ex.Message + "\n\n" + ex.InnerException + "\n\n" + ex.StackTrace); } } } } context.AddBulkSupplier(supCollection); string m = "save collection"; } catch (Exception ex) { // logger.Error("Error loading URL for " + URL + "\n\n" + ex.Message + "\n\n" + ex.InnerException + "\n\n" + ex.StackTrace); } } var FileUrl = Path.Combine(HttpContext.Current.Server.MapPath("~/UploadedFiles"), httpPostedFile.FileName); httpPostedFile.SaveAs(FileUrl); } } if (msgitemname != null) { return(msgitemname); } msg = "Your Exel data is succesfully saved"; return(msg); }
protected void HandFineSave(String FileName, int Id, FilesUpScope fp, String FilesKind, Boolean pdfConvertImage) { Stream upFileStream = Request.InputStream; BinaryReader BinRead = new BinaryReader(upFileStream); String FileExt = System.IO.Path.GetExtension(FileName); #region IE file stream handle String[] IEOlderVer = new string[] { "6.0", "7.0", "8.0", "9.0" }; System.Web.HttpPostedFile GetPostFile = null; if (Request.Browser.Browser == "IE" && IEOlderVer.Any(x => x == Request.Browser.Version)) { System.Web.HttpFileCollection collectFiles = System.Web.HttpContext.Current.Request.Files; GetPostFile = collectFiles[0]; if (!GetPostFile.FileName.Equals("")) { //GetFileName = System.IO.Path.GetFileName(GetPostFile.FileName); BinRead = new BinaryReader(GetPostFile.InputStream); } } Byte[] fileContents = { }; //const int bufferSize = 1024; //set 1k buffer while (BinRead.BaseStream.Position < BinRead.BaseStream.Length - 1) { Byte[] buffer = new Byte[BinRead.BaseStream.Length - 1]; int ReadLen = BinRead.Read(buffer, 0, buffer.Length); Byte[] dummy = fileContents.Concat(buffer).ToArray(); fileContents = dummy; dummy = null; } #endregion String tpl_Org_FolderPath = String.Format(SystemUpFilePathTpl, GetArea, GetController, Id, FilesKind, "OriginFile"); String Org_Path = Server.MapPath(tpl_Org_FolderPath); #region 檔案上傳前檢查 if (fp.LimitSize > 0) { //if (GetPostFile.InputStream.Length > fp.LimitSize) if (BinRead.BaseStream.Length > fp.LimitSize) { throw new LogicError("Log_Err_FileSizeOver"); } } if (fp.LimitCount > 0 && Directory.Exists(Org_Path)) { String[] Files = Directory.GetFiles(Org_Path); if (Files.Count() >= fp.LimitCount) //還沒存檔,因此Selet到等於的數量,再加上現在要存的檔案即算超過 { throw new LogicError("Log_Err_FileCountOver"); } } if (fp.AllowExtType != null) { if (!fp.AllowExtType.Contains(FileExt.ToLower())) { throw new LogicError("Log_Err_AllowFileType"); } } if (fp.LimitExtType != null) { if (fp.LimitExtType.Contains(FileExt)) { throw new LogicError("Log_Err_LimitedFileType"); } } #endregion #region 存檔區 if (!System.IO.Directory.Exists(Org_Path)) { System.IO.Directory.CreateDirectory(Org_Path); } //LogWrite.Write("Save File Start"+ Org_Path + "\\" + FileName); FileStream writeStream = new FileStream(Org_Path + "\\" + FileName, FileMode.Create); BinaryWriter BinWrite = new BinaryWriter(writeStream); BinWrite.Write(fileContents); //GetPostFile.SaveAs(Org_Path + "\\" + FileName); upFileStream.Close(); upFileStream.Dispose(); writeStream.Close(); BinWrite.Close(); writeStream.Dispose(); BinWrite.Dispose(); //LogWrite.Write("Save File End"+ Org_Path + "\\" + FileName); #endregion #region PDF轉圖檔 if (pdfConvertImage) { FileInfo fi = new FileInfo(Org_Path + "\\" + FileName); if (fi.Extension == ".pdf") { System.Diagnostics.Process proc = new System.Diagnostics.Process(); proc.StartInfo.UseShellExecute = false; proc.StartInfo.FileName = @"C:\Program Files\Boxoft PDF to JPG (freeware)\pdftojpg.exe"; proc.StartInfo.Arguments = Org_Path + "\\" + FileName + " " + Org_Path; proc.StartInfo.RedirectStandardInput = true; proc.StartInfo.RedirectStandardOutput = true; proc.StartInfo.RedirectStandardError = true; proc.Start(); proc.WaitForExit(); proc.Close(); proc.Dispose(); } } #endregion }
private void UploadImage(System.Web.HttpContext context, System.Web.HttpPostedFile file, string snailtype) { string str = "/storage/data/grade"; string text = System.Guid.NewGuid().ToString("N", System.Globalization.CultureInfo.InvariantCulture) + System.IO.Path.GetExtension(file.FileName); string str2 = str + "/images/" + text; if (this.uploadType.ToLower() == UploadType.SharpPic.ToString().ToLower()) { str = "/Storage/data/Sharp/"; text = System.DateTime.Now.ToString("yyyyMMddHHmmss") + System.IO.Path.GetExtension(file.FileName); str2 = str + text; } else if (this.uploadType.ToLower() == UploadType.Vote.ToString().ToLower()) { str = "/Storage/master/vote/"; str2 = str + text; } else if (this.uploadType.ToLower() == UploadType.Topic.ToString().ToLower()) { str = "/Storage/master/topic/"; str2 = str + text; } else if (this.uploadType.ToLower() == UploadType.Weibo.ToString().ToLower()) { str = "/Storage/master/Weibo/"; str2 = str + text; } if (this.uploadType.ToLower() == UploadType.Brand.ToString().ToLower()) { str = "/Storage/master/brand/"; str2 = str + text; } else if (this.uploadType.ToLower() == UploadType.ShopMenu.ToString().ToLower()) { str = "/Storage/master/ShopMenu/"; str2 = str + text; int num = 0; if (!string.IsNullOrEmpty(this.uploadSize)) { if (!int.TryParse(this.uploadSize, out num)) { this.WriteBackError(context, "UploadSize属性值只能是数字!"); return; } if (file.ContentLength > num) { this.WriteBackError(context, "文件大小不超过10KB!"); return; } } string text2 = System.IO.Path.GetExtension(file.FileName).ToLower(); if (!text2.Equals(".gif") && !text2.Equals(".jpg") && !text2.Equals(".jpeg") && !text2.Equals(".png") && !text2.Equals(".bmp")) { this.WriteBackError(context, "请上传正确的图片文件。"); return; } } string str3 = str + "/thumbs40/40_" + text; string str4 = str + "/thumbs60/60_" + text; string str5 = str + "/thumbs100/100_" + text; string str6 = str + "/thumbs160/160_" + text; string str7 = str + "/thumbs180/180_" + text; string str8 = str + "/thumbs220/220_" + text; string str9 = str + "/thumbs310/310_" + text; string str10 = str + "/thumbs410/410_" + text; file.SaveAs(context.Request.MapPath(Globals.ApplicationPath + str2)); string sourceFilename = context.Request.MapPath(Globals.ApplicationPath + str2); if (snailtype == "1") { ResourcesHelper.CreateThumbnail(sourceFilename, context.Request.MapPath(Globals.ApplicationPath + str3), 40, 40); ResourcesHelper.CreateThumbnail(sourceFilename, context.Request.MapPath(Globals.ApplicationPath + str4), 60, 60); ResourcesHelper.CreateThumbnail(sourceFilename, context.Request.MapPath(Globals.ApplicationPath + str5), 100, 100); ResourcesHelper.CreateThumbnail(sourceFilename, context.Request.MapPath(Globals.ApplicationPath + str6), 160, 160); ResourcesHelper.CreateThumbnail(sourceFilename, context.Request.MapPath(Globals.ApplicationPath + str7), 180, 180); ResourcesHelper.CreateThumbnail(sourceFilename, context.Request.MapPath(Globals.ApplicationPath + str8), 220, 220); ResourcesHelper.CreateThumbnail(sourceFilename, context.Request.MapPath(Globals.ApplicationPath + str9), 310, 310); ResourcesHelper.CreateThumbnail(sourceFilename, context.Request.MapPath(Globals.ApplicationPath + str10), 410, 410); } string[] value = new string[] { "'" + this.uploadType + "'", "'" + this.uploaderId + "'", "'" + str2 + "'", string.Concat(new string[] { "'", snailtype, "','", this.uploadSize, "'" }) }; context.Response.Write("<script type=\"text/javascript\">window.parent.UploadCallback(" + string.Join(",", value) + ");</script>"); }
public override void Process() { byte[] array = null; string text = null; if (this.UploadConfig.Base64) { text = this.UploadConfig.Base64Filename; array = System.Convert.FromBase64String(base.Request[this.UploadConfig.UploadFieldName]); } else { System.Web.HttpPostedFile httpPostedFile = base.Request.Files[this.UploadConfig.UploadFieldName]; text = httpPostedFile.FileName; if (!this.CheckFileType(text)) { this.Result.State = UploadState.TypeNotAllow; this.WriteResult(); return; } if (!this.CheckFileSize(httpPostedFile.ContentLength)) { this.Result.State = UploadState.SizeLimitExceed; this.WriteResult(); return; } array = new byte[httpPostedFile.ContentLength]; try { httpPostedFile.InputStream.Read(array, 0, httpPostedFile.ContentLength); } catch (System.Exception) { this.Result.State = UploadState.NetworkError; this.WriteResult(); } } this.Result.OriginFileName = text; string text2 = PathFormatter.Format(text, this.UploadConfig.PathFormat); string path = base.Server.MapPath(text2); try { if (!System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(path))) { System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(path)); } System.IO.File.WriteAllBytes(path, array); this.Result.Url = text2; this.Result.State = UploadState.Success; } catch (System.Exception ex) { this.Result.State = UploadState.FileAccessError; this.Result.ErrorMessage = ex.Message; } finally { this.WriteResult(); } }
protected void HandImageSave(String FileName, int Id, ImageUpScope fp, String FilesKind) { Stream upFileStream = Request.InputStream; BinaryReader BinRead = new BinaryReader(upFileStream); String FileExt = System.IO.Path.GetExtension(FileName); #region IE file stream handle String[] IEOlderVer = new string[] { "6.0", "7.0", "8.0", "9.0" }; System.Web.HttpPostedFile GetPostFile = null; if (Request.Browser.Browser == "IE" && IEOlderVer.Any(x => x == Request.Browser.Version)) { System.Web.HttpFileCollection collectFiles = System.Web.HttpContext.Current.Request.Files; GetPostFile = collectFiles[0]; if (!GetPostFile.FileName.Equals("")) { //GetFileName = System.IO.Path.GetFileName(GetPostFile.FileName); BinRead = new BinaryReader(GetPostFile.InputStream); } } Byte[] fileContents = { }; //const int bufferSize = 1024 * 16; //set 16K buffer while (BinRead.BaseStream.Position < BinRead.BaseStream.Length - 1) { //Byte[] buffer = new Byte[bufferSize]; Byte[] buffer = new Byte[BinRead.BaseStream.Length - 1]; int ReadLen = BinRead.Read(buffer, 0, buffer.Length); Byte[] dummy = fileContents.Concat(buffer).ToArray(); fileContents = dummy; dummy = null; } #endregion String tpl_Org_FolderPath = String.Format(SystemUpFilePathTpl, GetArea, GetController, Id, FilesKind, "OriginFile"); String Org_Path = Server.MapPath(tpl_Org_FolderPath); #region 檔案上傳前檢查 if (fp.LimitSize > 0) { //if (GetPostFile.InputStream.Length > fp.LimitSize) if (BinRead.BaseStream.Length > fp.LimitSize) { throw new LogicError("Log_Err_FileSizeOver"); } } if (fp.LimitCount > 0 && Directory.Exists(Org_Path)) { String[] Files = Directory.GetFiles(Org_Path); if (Files.Count() >= fp.LimitCount) //還沒存檔,因此Selet到等於的數量,再加上現在要存的檔案即算超過 { throw new LogicError("Log_Err_FileCountOver"); } } if (fp.AllowExtType != null) { if (!fp.AllowExtType.Contains(FileExt.ToLower())) { throw new LogicError("Log_Err_AllowFileType"); } } if (fp.LimitExtType != null) { if (fp.LimitExtType.Contains(FileExt)) { throw new LogicError("Log_Err_LimitedFileType"); } } #endregion #region 存檔區 if (fp.KeepOriginImage) { //原始檔 //tpl_Org_FolderPath = String.Format(SystemUpFilePathTpl, GetArea, GetController, Id, FilesKind, "OriginFile"); Org_Path = Server.MapPath(tpl_Org_FolderPath); if (!System.IO.Directory.Exists(Org_Path)) { System.IO.Directory.CreateDirectory(Org_Path); } FileStream writeStream = new FileStream(Org_Path + "\\" + FileName, FileMode.Create); BinaryWriter BinWrite = new BinaryWriter(writeStream); BinWrite.Write(fileContents); upFileStream.Close(); upFileStream.Dispose(); writeStream.Close(); BinWrite.Close(); writeStream.Dispose(); BinWrite.Dispose(); //FileName.SaveAs(Org_Path + "\\" + FileName.FileName.GetFileName()); } //後台管理的代表小圖 String tpl_Rep_FolderPath = String.Format(SystemUpFilePathTpl, GetArea, GetController, Id, FilesKind, "RepresentICON"); String Rep_Path = Server.MapPath(tpl_Rep_FolderPath); if (!System.IO.Directory.Exists(Rep_Path)) { System.IO.Directory.CreateDirectory(Rep_Path); } MemoryStream smr = UpFileReSizeImage(fileContents, 0, 90); System.IO.File.WriteAllBytes(Rep_Path + "\\" + FileName.GetFileName(), smr.ToArray()); smr.Dispose(); if (fp.Parm.Count() > 0) { foreach (ImageSizeParm imSize in fp.Parm) { tpl_Rep_FolderPath = String.Format(SystemUpFilePathTpl, GetArea, GetController, Id, FilesKind, "s_" + imSize.SizeFolder); Rep_Path = Server.MapPath(tpl_Rep_FolderPath); if (!System.IO.Directory.Exists(Rep_Path)) { System.IO.Directory.CreateDirectory(Rep_Path); } MemoryStream sm = UpFileReSizeImage(fileContents, imSize.width, imSize.heigh); System.IO.File.WriteAllBytes(Rep_Path + "\\" + FileName.GetFileName(), sm.ToArray()); sm.Dispose(); } } #endregion }
/// <summary> /// 指定长宽裁剪 /// 按模版比例最大范围的裁剪图片并缩放至模版尺寸 /// </summary> /// <param name="postedFile">原图HttpPostedFile对象</param> /// <param name="fileSaveUrl">保存路径</param> /// <param name="maxWidth">最大宽(单位:px)</param> /// <param name="maxHeight">最大高(单位:px)</param> /// <param name="quality">质量(范围0-100)</param> public static void CutForCustom(System.Web.HttpPostedFile postedFile, string fileSaveUrl, int maxWidth, int maxHeight, int quality) { //从文件获取原始图片,并使用流中嵌入的颜色管理信息 System.Drawing.Image initImage = System.Drawing.Image.FromStream(postedFile.InputStream, true); //原图宽高均小于模版,不作处理,直接保存 if (initImage.Width <= maxWidth && initImage.Height <= maxHeight) { initImage.Save(fileSaveUrl, System.Drawing.Imaging.ImageFormat.Jpeg); } else { //模版的宽高比例 double templateRate = (double)maxWidth / maxHeight; //原图片的宽高比例 double initRate = (double)initImage.Width / initImage.Height; //原图与模版比例相等,直接缩放 if (templateRate == initRate) { //按模版大小生成最终图片 System.Drawing.Image templateImage = new System.Drawing.Bitmap(maxWidth, maxHeight); System.Drawing.Graphics templateG = System.Drawing.Graphics.FromImage(templateImage); templateG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; templateG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; templateG.Clear(Color.White); templateG.DrawImage(initImage, new System.Drawing.Rectangle(0, 0, maxWidth, maxHeight), new System.Drawing.Rectangle(0, 0, initImage.Width, initImage.Height), System.Drawing.GraphicsUnit.Pixel); templateImage.Save(fileSaveUrl, System.Drawing.Imaging.ImageFormat.Jpeg); } //原图与模版比例不等,裁剪后缩放 else { //裁剪对象 System.Drawing.Image pickedImage = null; System.Drawing.Graphics pickedG = null; //定位 Rectangle fromR = new Rectangle(0, 0, 0, 0); //原图裁剪定位 Rectangle toR = new Rectangle(0, 0, 0, 0); //目标定位 //宽为标准进行裁剪 if (templateRate > initRate) { //裁剪对象实例化 pickedImage = new System.Drawing.Bitmap(initImage.Width, (int)Math.Floor(initImage.Width / templateRate)); pickedG = System.Drawing.Graphics.FromImage(pickedImage); //裁剪源定位 fromR.X = 0; fromR.Y = (int)Math.Floor((initImage.Height - initImage.Width / templateRate) / 2); fromR.Width = initImage.Width; fromR.Height = (int)Math.Floor(initImage.Width / templateRate); //裁剪目标定位 toR.X = 0; toR.Y = 0; toR.Width = initImage.Width; toR.Height = (int)Math.Floor(initImage.Width / templateRate); } //高为标准进行裁剪 else { pickedImage = new System.Drawing.Bitmap((int)Math.Floor(initImage.Height * templateRate), initImage.Height); pickedG = System.Drawing.Graphics.FromImage(pickedImage); fromR.X = (int)Math.Floor((initImage.Width - initImage.Height * templateRate) / 2); fromR.Y = 0; fromR.Width = (int)Math.Floor(initImage.Height * templateRate); fromR.Height = initImage.Height; toR.X = 0; toR.Y = 0; toR.Width = (int)Math.Floor(initImage.Height * templateRate); toR.Height = initImage.Height; } //设置质量 pickedG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; pickedG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; //裁剪 pickedG.DrawImage(initImage, toR, fromR, System.Drawing.GraphicsUnit.Pixel); //按模版大小生成最终图片 System.Drawing.Image templateImage = new System.Drawing.Bitmap(maxWidth, maxHeight); System.Drawing.Graphics templateG = System.Drawing.Graphics.FromImage(templateImage); templateG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; templateG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; templateG.Clear(Color.White); templateG.DrawImage(pickedImage, new System.Drawing.Rectangle(0, 0, maxWidth, maxHeight), new System.Drawing.Rectangle(0, 0, pickedImage.Width, pickedImage.Height), System.Drawing.GraphicsUnit.Pixel); //关键质量控制 //获取系统编码类型数组,包含了jpeg,bmp,png,gif,tiff ImageCodecInfo[] icis = ImageCodecInfo.GetImageEncoders(); ImageCodecInfo ici = null; foreach (ImageCodecInfo i in icis) { if (i.MimeType == "image/jpeg" || i.MimeType == "image/bmp" || i.MimeType == "image/png" || i.MimeType == "image/gif") { ici = i; } } EncoderParameters ep = new EncoderParameters(1); ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)quality); //保存缩略图 templateImage.Save(fileSaveUrl, ici, ep); //templateImage.Save(fileSaveUrl, System.Drawing.Imaging.ImageFormat.Jpeg); //释放资源 templateG.Dispose(); templateImage.Dispose(); pickedG.Dispose(); pickedImage.Dispose(); } } //释放资源 initImage.Dispose(); }
/// <summary> /// 正方型裁剪 /// 以图片中心为轴心,截取正方型,然后等比缩放 /// 用于头像处理 /// </summary> /// <param name="postedFile">原图HttpPostedFile对象</param> /// <param name="fileSaveUrl">缩略图存放地址</param> /// <param name="side">指定的边长(正方型)</param> /// <param name="quality">质量(范围0-100)</param> public static void CutForSquare(System.Web.HttpPostedFile postedFile, string fileSaveUrl, int side, int quality) { //创建目录 string dir = Path.GetDirectoryName(fileSaveUrl); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } //原始图片(获取原始图片创建对象,并使用流中嵌入的颜色管理信息) System.Drawing.Image initImage = System.Drawing.Image.FromStream(postedFile.InputStream, true); //原图宽高均小于模版,不作处理,直接保存 if (initImage.Width <= side && initImage.Height <= side) { initImage.Save(fileSaveUrl, System.Drawing.Imaging.ImageFormat.Jpeg); } else { //原始图片的宽、高 int initWidth = initImage.Width; int initHeight = initImage.Height; //非正方型先裁剪为正方型 if (initWidth != initHeight) { //截图对象 System.Drawing.Image pickedImage = null; System.Drawing.Graphics pickedG = null; //宽大于高的横图 if (initWidth > initHeight) { //对象实例化 pickedImage = new System.Drawing.Bitmap(initHeight, initHeight); pickedG = System.Drawing.Graphics.FromImage(pickedImage); //设置质量 pickedG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; pickedG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; //定位 Rectangle fromR = new Rectangle((initWidth - initHeight) / 2, 0, initHeight, initHeight); Rectangle toR = new Rectangle(0, 0, initHeight, initHeight); //画图 pickedG.DrawImage(initImage, toR, fromR, System.Drawing.GraphicsUnit.Pixel); //重置宽 initWidth = initHeight; } //高大于宽的竖图 else { //对象实例化 pickedImage = new System.Drawing.Bitmap(initWidth, initWidth); pickedG = System.Drawing.Graphics.FromImage(pickedImage); //设置质量 pickedG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; pickedG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; //定位 Rectangle fromR = new Rectangle(0, (initHeight - initWidth) / 2, initWidth, initWidth); Rectangle toR = new Rectangle(0, 0, initWidth, initWidth); //画图 pickedG.DrawImage(initImage, toR, fromR, System.Drawing.GraphicsUnit.Pixel); //重置高 initHeight = initWidth; } //将截图对象赋给原图 initImage = (System.Drawing.Image)pickedImage.Clone(); //释放截图资源 pickedG.Dispose(); pickedImage.Dispose(); } //缩略图对象 System.Drawing.Image resultImage = new System.Drawing.Bitmap(side, side); System.Drawing.Graphics resultG = System.Drawing.Graphics.FromImage(resultImage); //设置质量 resultG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; resultG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; //用指定背景色清空画布 resultG.Clear(Color.White); //绘制缩略图 resultG.DrawImage(initImage, new System.Drawing.Rectangle(0, 0, side, side), new System.Drawing.Rectangle(0, 0, initWidth, initHeight), System.Drawing.GraphicsUnit.Pixel); //关键质量控制 //获取系统编码类型数组,包含了jpeg,bmp,png,gif,tiff ImageCodecInfo[] icis = ImageCodecInfo.GetImageEncoders(); ImageCodecInfo ici = null; foreach (ImageCodecInfo i in icis) { if (i.MimeType == "image/jpeg" || i.MimeType == "image/bmp" || i.MimeType == "image/png" || i.MimeType == "image/gif") { ici = i; } } EncoderParameters ep = new EncoderParameters(1); ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)quality); //保存缩略图 resultImage.Save(fileSaveUrl, ici, ep); //释放关键质量控制所用资源 ep.Dispose(); //释放缩略图资源 resultG.Dispose(); resultImage.Dispose(); //释放原始图片资源 initImage.Dispose(); } }
/// <summary> /// 方法 -- 压缩图片 /// </summary> /// <param name="file">文件流</param> /// <param name="mode">文件夹名称</param> /// <param name="filename">返回文件名称</param> /// <returns></returns> public bool MakeThumbImg(System.Web.HttpPostedFile file, ref string filename) { string[] sArray = uploadArray; string fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + Common.Number(4, false); if (file.ContentLength > 0) { System.IO.FileInfo _file = new System.IO.FileInfo(file.FileName); string _fileExt = _file.Extension.ToLower(), _fileName = fileName + _fileExt; filename = _fileName; if (!Common.ArrayIsContains(sArray[18], _fileExt.Substring(1), ',')) { return(false); } string o_filename = sArray[16] + "/original/", s_filename = sArray[16] + "/images/"; //检测文件目录是否存在 FileUtils.CreateFile(o_filename); o_filename = o_filename + _fileName; //保存原图 file.SaveAs(Common.getAbsolutePath(o_filename)); //创建图片路径 FileUtils.CreateFile(s_filename); string[] wd_Array = sArray[1].Split(','), he_Array = sArray[2].Split(','); if (wd_Array.Length != he_Array.Length) { return(false); } else { for (int i = 0, len = wd_Array.Length; i < len; i++) { string imageName = s_filename + "JD" + i.ToString() + "_" + filename; MakeThumbnail(o_filename, imageName, Common.S_Int(wd_Array[i]), Common.S_Int(he_Array[i]), sArray[0], Common.S_Int(sArray[6])); ///开启图片水印 if (sArray[3] == "1") { AddImageSignPic(imageName, s_filename + "JD_p_water" + i.ToString() + filename, sArray[4], sArray[5], Common.S_Int(sArray[6]), 1); } ///开启文字水印 if (sArray[8] == "1") { AddImageSignText(imageName, s_filename + "JD_w_water" + i.ToString() + filename, sArray[12], sArray[5], Common.S_Int(sArray[6]), sArray[9], Common.S_Int(sArray[11]), sArray[10]); } } } return(true); } else { return(false); } }
/// <summary> /// 图片等比缩放并添加水印 /// </summary> /// <param name="postedFile">原图HttpPostedFile对象</param> /// <param name="savePath">缩略图存放地址</param> /// <param name="targetWidth">指定的最大宽度</param> /// <param name="targetHeight">指定的最大高度</param> /// <param name="watermarkText">水印文字(为""表示不使用水印)</param> /// <param name="watermarkImage">水印图片路径(为""表示不使用水印)</param> /// <param name="waterTextFont">文字水印字体</param> public static void ZoomAuto(System.Web.HttpPostedFile postedFile, string savePath, System.Double targetWidth, System.Double targetHeight, string watermarkText, string watermarkImage, Font waterTextFont) { //创建目录 string dir = Path.GetDirectoryName(savePath); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } if (waterTextFont == null) { waterTextFont = new Font("黑体", 14, GraphicsUnit.Pixel); } //原始图片(获取原始图片创建对象,并使用流中嵌入的颜色管理信息) System.Drawing.Image initImage = System.Drawing.Image.FromStream(postedFile.InputStream, true); //原图宽高均小于模版,不作处理,直接保存 if (initImage.Width <= targetWidth && initImage.Height <= targetHeight) { //文字水印 if (watermarkText != "") { using (System.Drawing.Graphics gWater = System.Drawing.Graphics.FromImage(initImage)) { System.Drawing.Font fontWater = waterTextFont; System.Drawing.Brush brushWater = new SolidBrush(Color.White); gWater.DrawString(watermarkText, fontWater, brushWater, 10, 10); gWater.Dispose(); } } //透明图片水印 if (watermarkImage != "") { if (File.Exists(watermarkImage)) { //获取水印图片 using (System.Drawing.Image wrImage = System.Drawing.Image.FromFile(watermarkImage)) { //水印绘制条件:原始图片宽高均大于或等于水印图片 if (initImage.Width >= wrImage.Width && initImage.Height >= wrImage.Height) { Graphics gWater = Graphics.FromImage(initImage); //透明属性 ImageAttributes imgAttributes = new ImageAttributes(); ColorMap colorMap = new ColorMap(); colorMap.OldColor = Color.FromArgb(255, 0, 255, 0); colorMap.NewColor = Color.FromArgb(0, 0, 0, 0); ColorMap[] remapTable = { colorMap }; imgAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap); float[][] colorMatrixElements = { new float[] { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f }, new float[] { 0.0f, 1.0f, 0.0f, 0.0f, 0.0f }, new float[] { 0.0f, 0.0f, 1.0f, 0.0f, 0.0f }, new float[] { 0.0f, 0.0f, 0.0f, 0.5f, 0.0f },//透明度:0.5 new float[] { 0.0f, 0.0f, 0.0f, 0.0f, 1.0f } }; ColorMatrix wmColorMatrix = new ColorMatrix(colorMatrixElements); imgAttributes.SetColorMatrix(wmColorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap); gWater.DrawImage(wrImage, new Rectangle(initImage.Width - wrImage.Width, initImage.Height - wrImage.Height, wrImage.Width, wrImage.Height), 0, 0, wrImage.Width, wrImage.Height, GraphicsUnit.Pixel, imgAttributes); gWater.Dispose(); } wrImage.Dispose(); } } } //保存 initImage.Save(savePath, System.Drawing.Imaging.ImageFormat.Jpeg); } else { //缩略图宽、高计算 double newWidth = initImage.Width; double newHeight = initImage.Height; //宽大于高或宽等于高(横图或正方) if (initImage.Width > initImage.Height || initImage.Width == initImage.Height) { //如果宽大于模版 if (initImage.Width > targetWidth) { //宽按模版,高按比例缩放 newWidth = targetWidth; newHeight = initImage.Height * (targetWidth / initImage.Width); } } //高大于宽(竖图) else { //如果高大于模版 if (initImage.Height > targetHeight) { //高按模版,宽按比例缩放 newHeight = targetHeight; newWidth = initImage.Width * (targetHeight / initImage.Height); } } //生成新图 //新建一个bmp图片 System.Drawing.Image newImage = new System.Drawing.Bitmap((int)newWidth, (int)newHeight); //新建一个画板 System.Drawing.Graphics newG = System.Drawing.Graphics.FromImage(newImage); //设置质量 newG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; newG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; //置背景色 newG.Clear(Color.White); //画图 newG.DrawImage(initImage, new System.Drawing.Rectangle(0, 0, newImage.Width, newImage.Height), new System.Drawing.Rectangle(0, 0, initImage.Width, initImage.Height), System.Drawing.GraphicsUnit.Pixel); //文字水印 if (watermarkText != "") { using (System.Drawing.Graphics gWater = System.Drawing.Graphics.FromImage(newImage)) { System.Drawing.Font fontWater = waterTextFont; System.Drawing.Brush brushWater = new SolidBrush(Color.White); gWater.DrawString(watermarkText, fontWater, brushWater, 10, 10); gWater.Dispose(); } } //透明图片水印 if (watermarkImage != "") { if (File.Exists(watermarkImage)) { //获取水印图片 using (System.Drawing.Image wrImage = System.Drawing.Image.FromFile(watermarkImage)) { //水印绘制条件:原始图片宽高均大于或等于水印图片 if (newImage.Width >= wrImage.Width && newImage.Height >= wrImage.Height) { Graphics gWater = Graphics.FromImage(newImage); //透明属性 ImageAttributes imgAttributes = new ImageAttributes(); ColorMap colorMap = new ColorMap(); colorMap.OldColor = Color.FromArgb(255, 0, 255, 0); colorMap.NewColor = Color.FromArgb(0, 0, 0, 0); ColorMap[] remapTable = { colorMap }; imgAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap); float[][] colorMatrixElements = { new float[] { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f }, new float[] { 0.0f, 1.0f, 0.0f, 0.0f, 0.0f }, new float[] { 0.0f, 0.0f, 1.0f, 0.0f, 0.0f }, new float[] { 0.0f, 0.0f, 0.0f, 0.5f, 0.0f },//透明度:0.5 new float[] { 0.0f, 0.0f, 0.0f, 0.0f, 1.0f } }; ColorMatrix wmColorMatrix = new ColorMatrix(colorMatrixElements); imgAttributes.SetColorMatrix(wmColorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap); gWater.DrawImage(wrImage, new Rectangle(newImage.Width - wrImage.Width, newImage.Height - wrImage.Height, wrImage.Width, wrImage.Height), 0, 0, wrImage.Width, wrImage.Height, GraphicsUnit.Pixel, imgAttributes); gWater.Dispose(); } wrImage.Dispose(); } } } //保存缩略图 newImage.Save(savePath, System.Drawing.Imaging.ImageFormat.Jpeg); //释放资源 newG.Dispose(); newImage.Dispose(); initImage.Dispose(); } }
public string UploadFile() { if (HttpContext.Current.Request.Files.AllKeys.Any()) { logger.Info("start Item Upload Exel File: "); var identity = User.Identity as ClaimsIdentity; int compid = 0, userid = 0; // Access claims foreach (Claim claim in identity.Claims) { if (claim.Type == "compid") { compid = int.Parse(claim.Value); } if (claim.Type == "userid") { userid = int.Parse(claim.Value); } } // Get the uploaded image from the Files collection System.Web.HttpPostedFile httpPostedFile = HttpContext.Current.Request.Files["file"]; if (httpPostedFile != null) { // Validate the uploaded image(optional) byte[] buffer = new byte[httpPostedFile.ContentLength]; using (BinaryReader br = new BinaryReader(httpPostedFile.InputStream)) { br.Read(buffer, 0, buffer.Length); } XSSFWorkbook hssfwb; using (MemoryStream memStream = new MemoryStream()) { BinaryFormatter binForm = new BinaryFormatter(); memStream.Write(buffer, 0, buffer.Length); memStream.Seek(0, SeekOrigin.Begin); hssfwb = new XSSFWorkbook(memStream); string sSheetName = hssfwb.GetSheetName(0); ISheet sheet = hssfwb.GetSheet(sSheetName); AuthContext context = new AuthContext(); IRow rowData; ICell cellData = null; try { List <Area> CustCollection = new List <Area>(); for (int iRowIdx = 0; iRowIdx <= sheet.LastRowNum; iRowIdx++) // iRowIdx = 0; HeaderRow { if (iRowIdx == 0) { } else { rowData = sheet.GetRow(iRowIdx); cellData = rowData.GetCell(0); rowData = sheet.GetRow(iRowIdx); if (rowData != null) { Area cust = new Area(); try { cellData = rowData.GetCell(0); col0 = cellData == null ? "" : cellData.ToString(); if (col0.Trim() == "") { break; } cust.AreaName = col0.Trim(); CustCollection.Add(cust); } catch (Exception ex) { msgitemname = ex.Message; logger.Error("Error adding People in collection " + "\n\n" + ex.Message + "\n\n" + ex.InnerException + "\n\n" + ex.StackTrace + cust.AreaName); } } } } context.AddBulkArea(CustCollection); string m = "save collection"; logger.Info(m); } catch (Exception ex) { logger.Error("Error loading URL for \n\n" + ex.Message + "\n\n" + ex.InnerException + "\n\n" + ex.StackTrace); } } var FileUrl = Path.Combine(HttpContext.Current.Server.MapPath("~/UploadedFiles"), httpPostedFile.FileName); httpPostedFile.SaveAs(FileUrl); } } if (msgitemname != null) { return(msgitemname); } msg = "Your Exel data is succesfully saved"; return(msg); }
public IHttpActionResult UploadFiles() { Boolean bRet = false; Dictionary <string, object> RetData = new Dictionary <string, object>(); try { int iLen = 0; string sRootFolder = @"D://documents/alldocs/"; string sLocalFolder = "2018-04"; Dictionary <string, object> SearchData = new Dictionary <string, object>(); int ContentLength = 0; int iUploadedCnt = 0; string sPath = ""; string Comp_Code = HttpContext.Current.Request.Form["COMPCODE"]; string Folder_ID = System.Guid.NewGuid().ToString().ToUpper(); //sRootFolder = @"D://documents/alldocs/"; //sLocalFolder = "2018-04"; sRootFolder = HttpContext.Current.Request.Form["ROOT-FOLDER"]; sLocalFolder = HttpContext.Current.Request.Form["SUB-FOLDER"]; SearchData.Add("COMP_CODE", Comp_Code); SearchData.Add("BRANCH_CODE", HttpContext.Current.Request.Form["BRANCHCODE"]); SearchData.Add("PARENT_ID", HttpContext.Current.Request.Form["PARENTID"]); SearchData.Add("GROUP_ID", HttpContext.Current.Request.Form["GROUPID"]); SearchData.Add("TYPE", HttpContext.Current.Request.Form["TYPE"]); SearchData.Add("CATG_ID", HttpContext.Current.Request.Form["CATGID"]); SearchData.Add("CREATED_BY", HttpContext.Current.Request.Form["CREATEDBY"]); SearchData.Add("PATH", ""); SearchData.Add("FILENAME", ""); if (SearchData["GROUP_ID"].ToString() == "MAIL-FTP-ATTACHMENT" || SearchData["GROUP_ID"].ToString() == "INCREMENT-LETTER") { string File_Name = ""; string File_Type = ""; string File_Display_Name = ""; string Category = ""; sRootFolder = SearchData["PARENT_ID"].ToString();//set report folder - temp files Category = SearchData["CATG_ID"].ToString(); System.Web.HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files; // CHECK THE FILE COUNT. ContentLength = 0; for (int iCnt = 0; iCnt <= hfc.Count - 1; iCnt++) { System.Web.HttpPostedFile hpf = hfc[iCnt]; File_Name = Lib.GetFileName(sRootFolder, Folder_ID, Path.GetFileName(hpf.FileName).Trim().ToUpper().Replace(",", " ")); if (hpf.ContentLength > 0) { //SAVE THE FILES IN THE FOLDER. hpf.SaveAs(File_Name); iUploadedCnt = iUploadedCnt + 1; File_Display_Name = Path.GetFileName(hpf.FileName).Trim().ToUpper().Replace(",", " "); ContentLength += hpf.ContentLength; } } RetData.Add("filesize", ContentLength); RetData.Add("category", Category); RetData.Add("filename", File_Name); RetData.Add("filetype", File_Type); RetData.Add("filedisplayname", File_Display_Name); } else { //sPath = System.Web.Hosting.HostingEnvironment.MapPath("~/locker/"); sPath = @"{COMP_CODE}/{FOLDER}/{SUBFOLDER_ID}"; sPath = sPath.Replace("{COMP_CODE}", Comp_Code); sPath = sPath.Replace("{FOLDER}", sLocalFolder); sPath = sPath.Replace("{SUBFOLDER_ID}", Folder_ID); System.Web.HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files; // CHECK THE FILE COUNT. for (int iCnt = 0; iCnt <= hfc.Count - 1; iCnt++) { Lib.CreateFolder(sRootFolder + sPath); System.Web.HttpPostedFile hpf = hfc[iCnt]; if (hpf.ContentLength > 0) { //SAVE THE FILES IN THE FOLDER. hpf.SaveAs(sRootFolder + sPath + "/" + Path.GetFileName(hpf.FileName).Trim().ToUpper()); iUploadedCnt = iUploadedCnt + 1; SearchData["PKID"] = System.Guid.NewGuid().ToString().ToUpper(); SearchData["PATH"] = sPath; SearchData["FILENAME"] = Path.GetFileName(hpf.FileName).Trim().ToUpper(); if (hpf.ContentLength < 1024) { SearchData["SIZE"] = hpf.ContentLength.ToString() + " B"; } else { iLen = hpf.ContentLength / 1024; SearchData["SIZE"] = iLen.ToString() + " KB"; } using (UserService obj = new UserService()) bRet = obj.SaveDocuments(SearchData); } } // RETURN A MESSAGE. if (iUploadedCnt > 0) { RetData.Add("status", "OK"); } else { RetData.Add("status", "FAILED"); } } return(Ok(RetData)); } catch (Exception Ex) { return(ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.BadRequest, Ex.Message.ToString()))); } }
/// <summary> /// 通用图片上传类 /// </summary> /// <param name="PostedFile">HttpPostedFile控件</param> /// <param name="SaveFolder">保存路径【sys.config配置路径】</param> /// <returns>返回上传信息</returns> public ResponseMessage FileSaveAs(System.Web.HttpPostedFile PostedFile, string SaveFolder) { ResponseMessage rm = new ResponseMessage(); try { if (string.IsNullOrEmpty(PostedFile.FileName)) { TryError(rm, 4); return(rm); } Random rd = new Random(); int rdInt = rd.Next(1000, 9999); //重命名名称 string NewfileName = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString() + rdInt; //获取上传文件的扩展名 string sEx = System.IO.Path.GetExtension(PostedFile.FileName); if (!CheckValidExt(SetAllowFormat, sEx)) { TryError(rm, 2); return(rm); } //获取上传文件的大小 double PostFileSize = PostedFile.ContentLength / 1024.0 / 1024.0; if (PostFileSize > SetAllowSize) { TryError(rm, 3); return(rm); } if (!System.IO.Directory.Exists(SaveFolder)) { System.IO.Directory.CreateDirectory(SaveFolder); } rm.FileName = NewfileName + sEx; string fullPath = SaveFolder.Trim('\\') + "\\" + rm.FileName; rm.WebPath = "/" + fullPath.Replace(HttpContext.Current.Server.MapPath("~/"), "").Replace("\\", "/"); rm.filePath = fullPath; rm.Size = PostFileSize; PostedFile.SaveAs(fullPath); System.Drawing.Bitmap bmp = new Bitmap(fullPath); int realWidth = bmp.Width; int realHeight = bmp.Height; bmp.Dispose(); #region 检测图片宽度限制 if (SetMinWidth > 0) { if (realWidth < SetMinWidth) { TryError(rm, 7); return(rm); } } #endregion #region 监测图片宽度是否超过600,超过的话,自动压缩到600 if (SetLimitWidth && realWidth > SetMaxWidth) { int mWidth = SetMaxWidth; int mHeight = mWidth * realHeight / realWidth; string tempFile = SaveFolder + Guid.NewGuid().ToString() + sEx; File.Move(fullPath, tempFile); CreateSmallPhoto(tempFile, mWidth, mHeight, fullPath, "", ""); File.Delete(tempFile); } #endregion #region 压缩图片存储尺寸 if (sEx.ToLower() != ".gif") { CompressPhoto(fullPath, 100); } #endregion //生成缩略图片高宽 if (string.IsNullOrEmpty(SetSmallImgWidth)) { rm.Message = "上传成功,无缩略图"; return(rm); } string[] oWidthArray = SetSmallImgWidth.Split(','); string[] oHeightArray = SetSmallImgHeight.Split(','); if (oWidthArray.Length != oHeightArray.Length) { TryError(rm, 6); return(rm); } for (int i = 0; i < oWidthArray.Length; i++) { if (Convert.ToInt32(oWidthArray[i]) <= 0 || Convert.ToInt32(oHeightArray[i]) <= 0) { continue; } string sImg = SaveFolder.TrimEnd('\\') + '\\' + NewfileName + "_" + i.ToString() + sEx; //判断图片高宽是否大于生成高宽。否则用原图 if (realWidth > Convert.ToInt32(oWidthArray[i])) { if (SetCutImage) { CreateSmallPhoto(fullPath, Convert.ToInt32(oWidthArray[i]), Convert.ToInt32(oHeightArray[i]), sImg, "", ""); } else { CreateSmallPhoto(fullPath, Convert.ToInt32(oWidthArray[i]), Convert.ToInt32(oHeightArray[i]), sImg, "", "", CutMode.CutNo); } } else { if (SetCutImage) { CreateSmallPhoto(fullPath, realWidth, realHeight, sImg, "", ""); } else { CreateSmallPhoto(fullPath, realWidth, realHeight, sImg, "", "", CutMode.CutNo); } } } #region 给大图添加水印 if (!string.IsNullOrEmpty(SetPicWater)) { AttachPng(SetPicWater, fullPath); } else if (!string.IsNullOrEmpty(SetWordWater)) { AttachText(SetWordWater, fullPath); } #endregion } catch (Exception ex) { TryError(rm, ex.Message); } return(rm); }
//[SwaggerResponse(HttpStatusCode.OK, "", typeof(account))] //[SwaggerResponse(HttpStatusCode.InternalServerError, "", typeof(ResultMessage))] //[HttpPost()] //[Route("UploadFiles")] public string UploadFiles() { StringBuilder sblogs = new StringBuilder(); sblogs.AppendLine("UploadFiles start"); string strFileName = ""; int iUploadedCnt = 0; // DEFINE THE PATH WHERE WE WANT TO SAVE THE FILES. string sPath = ""; try { //sPath = System.Web.Hosting.HostingEnvironment.MapPath("~/Images/"); sPath = System.Web.Hosting.HostingEnvironment.MapPath("~/Images/UserImages/"); sblogs.AppendLine("sPath : " + sPath); System.Web.HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files; // CHECK THE FILE COUNT. for (int iCnt = 0; iCnt <= hfc.Count - 1; iCnt++) { System.Web.HttpPostedFile hpf = hfc[iCnt]; if (hpf.ContentLength > 0) { // CHECK IF THE SELECTED FILE(S) ALREADY EXISTS IN FOLDER. (AVOID DUPLICATE) // SAVE THE FILES IN THE FOLDER. Random rnum = new Random(); int generatedNo = rnum.Next(1, int.MaxValue); strFileName = generatedNo + "_" + Path.GetFileName(hpf.FileName); hpf.SaveAs(sPath + strFileName); iUploadedCnt = iUploadedCnt + 1; sblogs.AppendLine("iUploadedCnt : " + iUploadedCnt); } } // RETURN A STATUS MESSAGE. if (iUploadedCnt > 0) { strFileName = strFileName.Replace("\"", "").Trim(); string path = ConfigurationManager.AppSettings["logopath"].ToString(); path = path + "Images/UserImages/"; strFileName = strFileName + "," + path + strFileName; //strFileName = strFileName.Replace("\"", "").Trim(); //strFileName = strFileName.Replace('"', ' ').Trim(); sblogs.AppendLine("strFileName : " + strFileName); return(strFileName); } else { return("failed"); } } catch (Exception ex) { sblogs.AppendLine("exception : " + ex.Message); return(ex.Message); } Logging.AddtoLogFile(sblogs.ToString(), "uploadfile"); return(strFileName); }
/// <summary> /// 上传文件 /// </summary> private void SaveFiles(int meid, int forumid, int bid, int reid, out int kk) { //允许上传数量 int maxAddNum = Convert.ToInt32(ub.GetSub("UpAddNum", xmlPath)); int AddNum = 0; if (maxAddNum > 0) { //计算今天上传数量 AddNum = new BCW.BLL.Upfile().GetTodayCount(meid); } //遍历File表单元素 System.Web.HttpFileCollection files = System.Web.HttpContext.Current.Request.Files; //int j = 1; int j = files.Count; int k = 0; try { string GetFiles = string.Empty; for (int iFile = files.Count - 1; iFile > -1; iFile--) { //检查文件扩展名字 System.Web.HttpPostedFile postedFile = files[iFile]; string fileName, fileExtension; fileName = System.IO.Path.GetFileName(postedFile.FileName); string UpExt = ub.GetSub("UpaFileExt", xmlPath); int UpLength = Convert.ToInt32(ub.GetSub("UpaMaxFileSize", xmlPath)); if (fileName != "") { fileExtension = System.IO.Path.GetExtension(fileName).ToLower(); //检查是否允许上传格式 if (UpExt.IndexOf(fileExtension) == -1) { continue; } //非法上传 if (fileExtension == ".asp" || fileExtension == ".aspx" || fileExtension == ".jsp" || fileExtension == ".php" || fileExtension == ".asa" || fileExtension == ".cer" || fileExtension == ".cdx" || fileExtension == ".htr" || fileExtension == ".exe") { continue; } if (postedFile.ContentLength > Convert.ToInt32(UpLength * 1024)) { continue; } string DirPath = string.Empty; string prevDirPath = string.Empty; string Path = "/Files/bbs/" + meid + "/act/"; string prevPath = "/Files/bbs/" + meid + "/prev/"; int IsVerify = 0; if (FileTool.CreateDirectory(Path, out DirPath)) { //上传数量限制 if (maxAddNum > 0) { if (maxAddNum <= (AddNum + k)) { k = -k; if (k == 0) { k = -999; } break; } } //生成随机文件名 fileName = DT.getDateTimeNum() + iFile + fileExtension; string SavePath = System.Web.HttpContext.Current.Request.MapPath(DirPath) + fileName; postedFile.SaveAs(SavePath); //=============================图片木马检测,包括TXT=========================== string vSavePath = SavePath; if (fileExtension == ".txt" || fileExtension == ".gif" || fileExtension == ".jpg" || fileExtension == ".jpeg" || fileExtension == "png" || fileExtension == ".bmp") { bool IsPass = true; System.IO.StreamReader sr = new System.IO.StreamReader(vSavePath, System.Text.Encoding.Default); string strContent = sr.ReadToEnd().ToLower(); sr.Close(); string str = "system.|request|javascript|script |script>|.getfolder|.createfolder|.deletefolder|.createdirectory|.deletedirectory|.saveas|wscript.shell|script.encode|server.|.createobject|execute|activexobject|language="; foreach (string s in str.Split('|')) { if (strContent.IndexOf(s) != -1) { System.IO.File.Delete(vSavePath); IsPass = false; break; } } if (IsPass == false) { continue; } } //=============================图片木马检测,包括TXT=========================== //审核要求指示 int Verify = Utils.ParseInt(ub.GetSub("UpIsVerify", xmlPath)); //缩略图生成 if (fileExtension == ".gif" || fileExtension == ".jpg" || fileExtension == ".jpeg" || fileExtension == "png" || fileExtension == ".bmp") { int ThumbType = Convert.ToInt32(ub.GetSub("UpaThumbType", xmlPath)); int width = Convert.ToInt32(ub.GetSub("UpaWidth", xmlPath)); int height = Convert.ToInt32(ub.GetSub("UpaHeight", xmlPath)); if (ThumbType > 0) { try { bool pbool = false; if (ThumbType == 1) { pbool = true; } if (FileTool.CreateDirectory(prevPath, out prevDirPath)) { string prevSavePath = System.Web.HttpContext.Current.Request.MapPath(prevDirPath) + fileName; int IsThumb = 0; if (fileExtension == ".gif") { if (ThumbType > 0) { new BCW.Graph.GifHelper().GetThumbnail(SavePath, prevSavePath, width, height, pbool); } IsThumb = Convert.ToInt32(ub.GetSub("UpaIsThumb", xmlPath)); if (IsThumb > 0) { if (IsThumb == 1) { new BCW.Graph.GifHelper().SmartWaterMark(SavePath, "", ub.GetSub("UpaWord", xmlPath), ub.GetSub("UpaWordColor", xmlPath), "Arial", 12, Convert.ToInt32(ub.GetSub("UpaPosition", xmlPath)));//文字水印 } else { new BCW.Graph.GifHelper().WaterMark(SavePath, "", Server.MapPath(ub.GetSub("UpaWord", xmlPath)), Convert.ToInt32(ub.GetSub("UpaPosition", xmlPath)), Convert.ToInt32(ub.GetSub("UpaTran", xmlPath)));//图片水印 } } } else { if (fileExtension == ".gif" || fileExtension == ".jpg" || fileExtension == ".jpeg") { if (ThumbType > 0) { new BCW.Graph.ImageHelper().ResizeImage(SavePath, prevSavePath, width, height, pbool); } IsThumb = Convert.ToInt32(ub.GetSub("UpaIsThumb", xmlPath)); if (IsThumb > 0) { if (IsThumb == 1) { new BCW.Graph.ImageHelper().WaterMark(SavePath, "", ub.GetSub("UpaWord", xmlPath), ub.GetSub("UpaWordColor", xmlPath), "Arial", 12, Convert.ToInt32(ub.GetSub("UpaPosition", xmlPath)));//文字水印 } else { new BCW.Graph.ImageHelper().WaterMark(SavePath, "", Server.MapPath(ub.GetSub("UpaWord", xmlPath)), Convert.ToInt32(ub.GetSub("UpaPosition", xmlPath)), Convert.ToInt32(ub.GetSub("UpaTran", xmlPath)));//图片水印 } } } } } } catch { } } //图片审核 if (Verify > 0) { IsVerify = 1; } } else { //文件审核 if (Verify > 1) { IsVerify = 1; } } string Content = Utils.GetRequest("stext" + j + "", "post", 1, "", ""); if (!string.IsNullOrEmpty(Content)) { Content = Utils.Left(Content, 30); } else { Content = ""; } BCW.Model.Upfile model = new BCW.Model.Upfile(); model.Types = FileTool.GetExtType(fileExtension); model.NodeId = 0; model.UsID = meid; model.ForumID = forumid; model.BID = bid; model.ReID = reid; model.Files = DirPath + fileName; if (string.IsNullOrEmpty(prevDirPath)) { model.PrevFiles = model.Files; } else { model.PrevFiles = prevDirPath + fileName; } model.Content = Content; model.FileSize = Convert.ToInt64(postedFile.ContentLength); model.FileExt = fileExtension; model.DownNum = 0; model.Cent = 0; model.IsVerify = IsVerify; model.AddTime = DateTime.Now; new BCW.BLL.Upfile().Add(model); k++; } //j++; j--; } } } catch { } kk = k; }
protected void btnSaveImageData_Click(object sender, System.EventArgs e) { string value = this.RePlaceImg.Value; int photoId = System.Convert.ToInt32(this.RePlaceId.Value); string photoPath = GalleryHelper.GetPhotoPath(photoId); string a = photoPath.Substring(photoPath.LastIndexOf(".")); string b = string.Empty; string text = string.Empty; try { System.Web.HttpFileCollection files = base.Request.Files; System.Web.HttpPostedFile httpPostedFile = files[0]; b = System.IO.Path.GetExtension(httpPostedFile.FileName); if (a != b) { this.ShowMsgToTarget("上传图片类型与原文件类型不一致!", false, "parent"); } else { string str = Globals.GetStoragePath() + "/gallery"; text = photoPath.Substring(photoPath.LastIndexOf("/") + 1); string text2 = value.Substring(value.LastIndexOf("/") - 6, 6); string text3 = string.Empty; if (text2.ToLower().Contains("weibo")) { text3 = Globals.GetStoragePath() + "/weibo/"; } else { text3 = str + "/" + text2 + "/"; } int contentLength = httpPostedFile.ContentLength; string path = base.Request.MapPath(text3); //text2 + "/" + text; System.IO.DirectoryInfo directoryInfo = new System.IO.DirectoryInfo(path); if (!directoryInfo.Exists) { directoryInfo.Create(); } if (!ResourcesHelper.CheckPostedFile(httpPostedFile, "image")) { this.ShowMsgToTarget("文件上传的类型不正确!", false, "parent"); } else if (contentLength >= 2048000) { this.ShowMsgToTarget("图片文件已超过网站限制大小!", false, "parent"); } else { httpPostedFile.SaveAs(base.Request.MapPath(text3 + text)); GalleryHelper.ReplacePhoto(photoId, contentLength); this.CloseWindow(); } } } catch { this.ShowMsgToTarget("替换文件错误!", false, "parent"); } }
public HttpResponseMessage CreateCompany(CompanyModel _CompanyModel) { int iUploadedCnt = 0; try { bool conn = false; conn = db.Database.Exists(); if (!conn) { ConnectionTools.changeToLocalDB(db); conn = db.Database.Exists(); } if (conn) { // DEFINE THE PATH WHERE WE WANT TO SAVE THE FILES. string sPath = ""; sPath = System.Web.Hosting.HostingEnvironment.MapPath("~/Upload/"); System.Web.HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files; // CHECK THE FILE COUNT. for (int iCnt = 0; iCnt <= hfc.Count - 1; iCnt++) { System.Web.HttpPostedFile hpf = hfc[iCnt]; if (hpf.ContentLength > 0) { // CHECK IF THE SELECTED FILE(S) ALREADY EXISTS IN FOLDER. (AVOID DUPLICATE) if (!File.Exists(sPath + Path.GetFileName(hpf.FileName))) { // SAVE THE FILES IN THE FOLDER. hpf.SaveAs(sPath + Path.GetFileName(hpf.FileName)); iUploadedCnt = iUploadedCnt + 1; } } } TBL_COMPANY com = new TBL_COMPANY(); com.COMPANY_NAME = _CompanyModel.NAME; com.SHOPNAME = _CompanyModel.SHOPNAME; com.PREFIX = _CompanyModel.PREFIX; com.PREFIX_NUM = _CompanyModel.PREFIX_NUM; com.TIN_NUMBER = _CompanyModel.TIN_NUMBER; com.ADDRESS_1 = _CompanyModel.ADDRESS_1; com.ADDRESS_2 = _CompanyModel.ADDRESS_2; com.CITY = _CompanyModel.CITY; com.STATE = _CompanyModel.STATE; com.COUNTRY = _CompanyModel.COUNTRY; com.PIN = _CompanyModel.PIN; com.PHONE_NUMBER = _CompanyModel.PHONE_NUMBER; com.MOBILE_NUMBER = _CompanyModel.MOBILE_NUMBER; com.EMAIL = _CompanyModel.EMAIL; com.WEBSITE = _CompanyModel.WEBSITE; com.DEFAULT_TAX_RATE = _CompanyModel.DEFAULT_TAX_RATE; com.IS_WARNED_FOR_NEGATIVE_STOCK = _CompanyModel.IS_WARNED_FOR_NEGATIVE_STOCK; com.IS_WARNED_FOR_LESS_SALES_PRICE = _CompanyModel.IS_WARNED_FOR_LESS_SALES_PRICE; com.TAX_PRINTED_DESCRIPTION = _CompanyModel.TAX_PRINTED_DESCRIPTION; com.FIRST_DAY_OF_FINANCIAL_YEAR = _CompanyModel.FIRST_DAY_OF_FINANCIAL_YEAR; com.FIRST_MONTH_OF_FINANCIAL_YEAR = _CompanyModel.FIRST_MONTH_OF_FINANCIAL_YEAR; com.IMAGE_PATH = _CompanyModel.IMAGE_PATH; db.TBL_COMPANY.Add(com); db.SaveChanges(); int ID = com.COMAPNY_ID; TBL_BANK Bank = new TBL_BANK(); Bank.ADDRESS_1 = _CompanyModel.BANK_ADDRESS_1; Bank.ADDRESS_2 = _CompanyModel.BANK_ADDRESS_2; Bank.BANK_NAME = _CompanyModel.BANK_NAME; Bank.CITY = _CompanyModel.BANK_CITY; Bank.COMPANY_ID = ID; Bank.BANK_CODE = _CompanyModel.BANK_CODE; Bank.PIN_CODE = _CompanyModel.BANK_PIN_CODE; Bank.PHONE_NUMBER = _CompanyModel.BANK_PHONE_NUMBER; Bank.STATE = _CompanyModel.BANK_STATE; db.TBL_BANK.Add(Bank); db.SaveChanges(); long ba = Bank.BANK_ID; TBL_BANK_ACCOUNT ac = new TBL_BANK_ACCOUNT(); ac.ACCOUNT_NUMBER = _CompanyModel.ACCOUNT_NUMBER; ac.BRANCH_NAME = _CompanyModel.BRANCH_NAME; ac.COMPANY_ID = ID; ac.BANK_ID = ba; ac.BRANCH_NAME = _CompanyModel.BRANCH_NAME; db.TBL_BANK_ACCOUNT.Add(ac); db.SaveChanges(); TBL_GODOWN gd = new TBL_GODOWN(); gd.COMPANY_ID = ID; gd.GODOWN_NAME = _CompanyModel.NAME; gd.GOSOWN_DESCRIPTION = "Default Godown"; gd.IS_ACTIVE = true; gd.IS_DELETE = false; gd.IS_DEFAULT_GODOWN = true; return(Request.CreateResponse(HttpStatusCode.OK, com)); } else { return(Request.CreateResponse(HttpStatusCode.ExpectationFailed)); } } catch (Exception ex) { throw; } finally { ConnectionTools.ChangeToRemoteDB(db); } }
private async Task <HttpResponseMessage> UseMultipartFormDataStream() { string root = HttpContext.Current.Server.MapPath("~/images"); var provider = new MultipartFormDataStreamProvider(root); MultipartFormDataContent mpfdc = new MultipartFormDataContent(); // DEFINE THE PATH WHERE WE WANT TO SAVE THE FILES. string sPath = ""; sPath = System.Web.Hosting.HostingEnvironment.MapPath("~/images/"); System.Web.HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files; // CHECK THE FILE COUNT. for (int iCnt = 0; iCnt <= hfc.Count - 1; iCnt++) { System.Web.HttpPostedFile hpf = hfc[iCnt]; var filepath = string.Empty; var fileNamefuStamp = string.Empty; var physicalPathfuStamp = string.Empty; if (hpf.ContentLength > 0) { // CHECK IF THE SELECTED FILE(S) ALREADY EXISTS IN FOLDER. (AVOID DUPLICATE) if (!File.Exists(sPath + Path.GetFileName(hpf.FileName))) { // SAVE THE FILES IN THE FOLDER. Bitmap bitmapImage = ResizeImage(hpf.InputStream, 200, 200); System.IO.MemoryStream stream = new System.IO.MemoryStream(); bitmapImage.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp); var data = stream.ToArray(); // Random r = new Random(); // string code = r.Next().ToString(); // fileNamefuStamp = Path.GetFileName(code + hpf.FileName); // physicalPathfuStamp = Path.Combine(Server.MapPath("~/Models/"), fileNamefuStamp); //filepath = "\\images\\Partners\\" + code + x.FileName; //filepath = code + file.FileName; //File.WriteAllBytes(sPath + Path.GetFileName(hpf.FileName), (data as byte[])); //file.SaveAs(Server.MapPath("~/images/Partners/" + fileNamefuStamp)); //hpf.SaveAs(sPath + Path.GetFileName(hpf.FileName)); // iUploadedCnt = iUploadedCnt + 1; BasicInformaionEntities item = new BasicInformaionEntities(); item.EMPLOYEE_IMAGE = Path.GetFileName(hpf.FileName); item.EMPIMG = data; string s = hpf.FileName; int ix = s.IndexOf('_'); //s = ix != -1 ? s.Substring(ix + 1) : s; //using the ternary operator here is quite useless, better to write: //yourStringVariable.Substring(0, ix); s = s.Substring(0, ix); int id = Convert.ToInt32(new String(s.ToCharArray().Where(c => Char.IsDigit(c)).ToArray())); bool b = _Basicinfo.UpdateEmployeebasicinfo(id, item); } } //else //{ // return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ""); //} } var response = Request.CreateResponse(); response.StatusCode = HttpStatusCode.OK; return(response); //var file = provider.FileData; //if (file != null && file. > 0) //{ // var filename = file.Headers.ContentDisposition.FileName; // var path = Path.Combine(Server.MapPath("~/App_Data/"), fileName); // file.SaveAs(path); //} //try //{ // await Request.Content.ReadAsMultipartAsync(provider); // foreach (MultipartFileData file in provider.FileData) // { // var filename = file.Headers.ContentDisposition.FileName; // Trace.WriteLine(filename); // Trace.WriteLine("Server file path: " + file.LocalFileName); // mpfdc.Add(new ByteArrayContent(File.ReadAllBytes(file.LocalFileName)), "File", filename); // var path = Path.Combine(root, filename); // } // var response = Request.CreateResponse(); // response.Content = mpfdc; // response.StatusCode = HttpStatusCode.OK; // return response; //} //catch (System.Exception e) //{ // return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e); //} }
public async Task <HttpResponseMessage> SaveTickets() { httpResponseMessage = new HttpResponseMessage(); try { int TicketId = 0, DocumentId = 0; string UserEmail = ""; if (System.Web.HttpContext.Current.Request.Form.AllKeys.Length > 0) { TicketRequest ticketRequest = new TicketRequest(); // Show all the key-value pairs. foreach (var key in System.Web.HttpContext.Current.Request.Form.AllKeys) { foreach (var val in System.Web.HttpContext.Current.Request.Form.GetValues(key)) { switch (key) { case "Email": ticketRequest.Email = val; UserEmail = ticketRequest.Email; break; case "Subject": ticketRequest.Subject = val; break; case "Message": ticketRequest.Message = val; break; case "Department": ticketRequest.Department = val; break; case "Priority": ticketRequest.Priority = val; break; default: break; } } } TicketId = await _IAccountService.SaveTickets(ticketRequest); } else { httpResponseMessage = Request.CreateResponse(HttpStatusCode.OK, new { Message = CustomErrorMessages.INVALID_INPUTS, Success = false }); return(httpResponseMessage); } var listOfStrings = new List <string>(); System.Web.HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files; if (hfc.Count > 0 && TicketId > 0) { int iUploadedCnt = 0; // CHECK THE FILE COUNT. for (int iCnt = 0; iCnt <= hfc.Count - 1; iCnt++) { System.DateTime myDate = DateTime.Now; int year = myDate.Year; int month = myDate.Month; var PartialPath = "/Uploads/Documents/" + year + "/" + month + "/"; var FilePath = "~" + PartialPath; bool exists = System.IO.Directory.Exists(HttpContext.Current.Server.MapPath(FilePath)); if (!exists) { System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath(FilePath)); } System.Web.HttpPostedFile hpf = hfc[iCnt]; if (hpf.ContentLength > 0) { string FileName = "Ticket_" + Guid.NewGuid().ToString() + Path.GetExtension(hpf.FileName); // CHECK IF THE SELECTED FILE(S) ALREADY EXISTS IN FOLDER. (AVOID DUPLICATE) if (!File.Exists(FilePath + FileName)) { var FilePathWithFilename = Path.Combine(HttpContext.Current.Server.MapPath(FilePath), FileName); // SAVE THE FILES IN THE FOLDER. hpf.SaveAs(FilePathWithFilename); listOfStrings.Add(FilePathWithFilename); iUploadedCnt = iUploadedCnt + 1; Document document = new App.Repository.Document(); document.DocumentName = FileName; document.DocumentPath = PartialPath + "/" + FileName; DocumentId = await _IAccountService.SaveDocument(document); if (DocumentId > 0 && TicketId > 0) { TicketAttachment ticketAttachment = new TicketAttachment(); ticketAttachment.DocumentId = DocumentId; ticketAttachment.TicketId = TicketId; await _IAccountService.SaveTicketAttachment(ticketAttachment); } } } } } string[] fileAttachment = listOfStrings.ToArray(); TicketMailRequest ticketMailRequest = new TicketMailRequest(); ticketMailRequest.fileAttachments = fileAttachment; ticketMailRequest.ticketId = TicketId; ticketMailRequest.UserEmail = UserEmail; bool isMailSend = await _IAccountService.SendTicketMail(ticketMailRequest); if (isMailSend) { httpResponseMessage = Request.CreateResponse(HttpStatusCode.OK, new { Message = CustomErrorMessages.TICKET_SAVED_SUCCESSFULLY, Success = true }); } else { httpResponseMessage = Request.CreateResponse(HttpStatusCode.OK, new { Message = "Mail not sent", Success = false }); } } catch (System.Exception ex) { Elmah.ErrorSignal.FromCurrentContext().Raise(ex); httpResponseMessage = Request.CreateResponse(HttpStatusCode.OK, new { Message = CustomErrorMessages.INTERNAL_ERROR, Success = false }); } return(httpResponseMessage); }
public string UploadFile() { string ListDinhKem = "#"; try { string directoryPath = HttpContext.Current.Server.MapPath("~/Uploads"); string path1 = Request.RequestUri.GetLeftPart(UriPartial.Authority) + "/Uploads";;// Request.GetRequestContext().VirtualPathRoot;// Request.Url.GetLeftPart(UriPartial.Authority) + "/Uploads"; if (!Directory.Exists(directoryPath)) { Directory.CreateDirectory(directoryPath); } System.Web.HttpFileCollection httpRequest = System.Web.HttpContext.Current.Request.Files; using (var context = new WebApiDataEntities()) { using (DbContextTransaction transaction = context.Database.BeginTransaction()) { try { for (int i = 0; i <= httpRequest.Count - 1; i++) { string MaDinhKem = ""; MaDinhKem = Auto_ID("FILE"); var oDK = new FILE_DINH_KEM(); System.Web.HttpPostedFile postedfile = httpRequest[i]; if (postedfile.ContentLength > 0) { oDK.FCode = MaDinhKem; oDK.FName = postedfile.FileName; string Filesave = MaDinhKem + postedfile.FileName; if (Filesave.Length > 150) { Filesave = Filesave.Substring(0, 149); } var fileSavePath = Path.Combine(directoryPath, Filesave); if (File.Exists(fileSavePath)) { File.Delete(fileSavePath); } postedfile.SaveAs(fileSavePath); oDK.DuongDanFile = Path.Combine(path1, Filesave);// fileSavePath; if (MaDinhKem != "") { context.FILE_DINH_KEM.Add(oDK); context.SaveChanges(); ListDinhKem = ListDinhKem + MaDinhKem + "#"; } } } transaction.Commit(); } catch (Exception ex) { transaction.Rollback(); Commons.Common.WriteLogToTextFile(ex.ToString()); } } } } catch (Exception ex) { Commons.Common.WriteLogToTextFile(ex.ToString()); } return(ListDinhKem); }
protected void Page_Load(object sender, System.EventArgs e) { Hidistro.Membership.Core.IUser user = Hidistro.Membership.Context.Users.GetUser(0, Hidistro.Membership.Context.Users.GetLoggedOnUsername(), true, true); if (user.UserRole != Hidistro.Membership.Core.Enums.UserRole.SiteManager) { this.showError("您没有权限执行此操作!"); return; } string a = "false"; if (base.Request.Form["isAdvPositions"] != null) { a = base.Request.Form["isAdvPositions"].ToString().ToLower().Trim(); } if (a == "false") { this.savePath = "~/Storage/master/gallery/"; this.saveUrl = "/Storage/master/gallery/"; } else { this.savePath = string.Format("{0}/fckfiles/Files/Image/", Hidistro.Membership.Context.HiContext.Current.GetSkinPath()); if (base.Request.ApplicationPath != "/") { this.saveUrl = this.savePath.Substring(base.Request.ApplicationPath.Length); } else { this.saveUrl = this.savePath; } } int num = 0; if (base.Request.Form["fileCategory"] != null) { int.TryParse(base.Request.Form["fileCategory"], out num); } string text = string.Empty; if (base.Request.Form["imgTitle"] != null) { text = base.Request.Form["imgTitle"]; } System.Web.HttpPostedFile httpPostedFile = base.Request.Files["imgFile"]; if (httpPostedFile == null) { this.showError("请先选择文件!"); return; } if (!ResourcesHelper.CheckPostedFile(httpPostedFile)) { this.showError("不能上传空文件,且必须是有效的图片文件!"); return; } string text2 = base.Server.MapPath(this.savePath); if (!System.IO.Directory.Exists(text2)) { this.showError("上传目录不存在。"); return; } if (a == "false") { text2 += string.Format("{0}/", System.DateTime.Now.ToString("yyyyMM")); this.saveUrl += string.Format("{0}/", System.DateTime.Now.ToString("yyyyMM")); } if (!System.IO.Directory.Exists(text2)) { System.IO.Directory.CreateDirectory(text2); } string fileName = httpPostedFile.FileName; if (text.Length == 0) { text = fileName; } string str = System.IO.Path.GetExtension(fileName).ToLower(); string str2 = System.DateTime.Now.ToString("yyyyMMddHHmmss_ffff", System.Globalization.DateTimeFormatInfo.InvariantInfo) + str; string filename = text2 + str2; string text3 = this.saveUrl + str2; try { httpPostedFile.SaveAs(filename); if (a == "false") { Database database = DatabaseFactory.CreateDatabase(); System.Data.Common.DbCommand sqlStringCommand = database.GetSqlStringCommand("insert into Hishop_PhotoGallery(CategoryId,PhotoName,PhotoPath,FileSize,UploadTime,LastUpdateTime)values(@cid,@name,@path,@size,@time,@time1)"); database.AddInParameter(sqlStringCommand, "cid", System.Data.DbType.Int32, num); database.AddInParameter(sqlStringCommand, "name", System.Data.DbType.String, text); database.AddInParameter(sqlStringCommand, "path", System.Data.DbType.String, text3); database.AddInParameter(sqlStringCommand, "size", System.Data.DbType.Int32, httpPostedFile.ContentLength); database.AddInParameter(sqlStringCommand, "time", System.Data.DbType.DateTime, System.DateTime.Now); database.AddInParameter(sqlStringCommand, "time1", System.Data.DbType.DateTime, System.DateTime.Now); database.ExecuteNonQuery(sqlStringCommand); } } catch { this.showError("保存文件出错!"); } System.Collections.Hashtable hashtable = new System.Collections.Hashtable(); hashtable["error"] = 0; hashtable["url"] = Globals.ApplicationPath + text3; base.Response.AddHeader("Content-Type", "text/html; charset=UTF-8"); base.Response.Write(JsonMapper.ToJson(hashtable)); base.Response.End(); }
public async Task <IHttpActionResult> Upload() { try { var UserId = ((ClaimsIdentity)User.Identity).Claims.FirstOrDefault(c => c.Type.Equals(ClaimTypes.NameIdentifier)).Value; HttpFileCollection files = HttpContext.Current.Request.Files; Stream FileStream = null; IExcelDataReader reader = null; System.Web.HttpPostedFile Inputfile = files[0]; FileStream = Inputfile.InputStream; string message = ""; DataSet dsexcelRecords = new DataSet(); List <tblBrand> objBrand = new List <tblBrand>(); BaseModel baseModel = new BaseModel(); //using (DbContextTransaction transaction = entities.Database.BeginTransaction()) //{ if (Inputfile != null && FileStream != null) { if (Inputfile.FileName.EndsWith(".xls")) { reader = ExcelReaderFactory.CreateBinaryReader(FileStream); } else if (Inputfile.FileName.EndsWith(".xlsx")) { reader = ExcelReaderFactory.CreateOpenXmlReader(FileStream); } else { message = "The file format is not supported."; } dsexcelRecords = reader.AsDataSet(); reader.Close(); if (dsexcelRecords != null && dsexcelRecords.Tables.Count > 0) { DataTable dtBrandRecords = dsexcelRecords.Tables[0]; for (int i = 0; i < dtBrandRecords.Rows.Count; i++) { if (i > 0) { tblBrand objB = new tblBrand(); objB.BrandName = Convert.ToString(dtBrandRecords.Rows[i][0]); if (objB.BrandName == "") { baseModel.success = false; baseModel.message = "Brand Name is not exist!"; baseModel.code = 500; return(Ok(baseModel)); } var getBrandName = entities.tblBrands.Where(x => x.BrandName.ToLower() == objB.BrandName.ToLower()).FirstOrDefault(); if (getBrandName != null) { baseModel.success = false; baseModel.message = "Brand Name " + objB.BrandName + " already exist!"; baseModel.code = 500; return(Ok(baseModel)); } objB.BrandDescription = Convert.ToString(dtBrandRecords.Rows[i][1]); objB.CreatedBy = Convert.ToInt32(UserId); objB.CreatedOn = DateTime.Now; entities.tblBrands.Add(objB); } } entities.SaveChanges(); } } baseModel.success = true; baseModel.message = "File upload successfully."; baseModel.code = 200; return(Ok(baseModel)); } catch (Exception ex) { responseData.message = ex.Message != null?ex.Message.ToString() : "server error"; return(Ok(responseData)); } }
public override string StoreFile(System.Web.HttpPostedFile file, string path, string name, params string[] arguments) { return(StoreFile(Telerik.Web.UI.UploadedFile.FromHttpPostedFile(file), path, name, arguments)); }
public async Task <ResponseObject> Post() { FileUploadManager fileUploadManager = new FileUploadManager(); ResponseObject responseObject = new ResponseObject(); try { string email = WebConfigurationManager.AppSettings["pdfixEmail"]; string password = WebConfigurationManager.AppSettings["pdfixPassword"]; string fileSize = WebConfigurationManager.AppSettings["fileSize"]; string fileExtension = WebConfigurationManager.AppSettings["fileExtension"]; var resourcesDir = HttpContext.Current.Server.MapPath("~/UploadedFiles/"); var outputDir = HttpContext.Current.Server.MapPath("~/JSON/"); if (!Directory.Exists(resourcesDir)) { Directory.CreateDirectory(resourcesDir); } if (!Directory.Exists(outputDir)) { Directory.CreateDirectory(outputDir); } string fileName = string.Empty; System.Web.HttpFileCollection httpFileCollection = System.Web.HttpContext.Current.Request.Files; for (int count = 0; count <= httpFileCollection.Count - 1; count++) { System.Web.HttpPostedFile postedFile = httpFileCollection[count]; bool result = Convert.ToBoolean(fileSize.CompareTo(Convert.ToString(postedFile.ContentLength))); if (postedFile.ContentLength > 0) { if (!result) { responseObject.flag = false; responseObject.message = "Document size cannot be more than 8MB"; } if (postedFile.ContentType != fileExtension) { responseObject.flag = false; responseObject.message = "File type is not supported"; return(responseObject); } fileName = postedFile.FileName; var filePath = HttpContext.Current.Server.MapPath("~/UploadedFiles/" + postedFile.FileName); postedFile.SaveAs(filePath); } else { responseObject.flag = false; responseObject.message = "Please upload file"; return(responseObject); } } responseObject = await fileUploadManager.TemplateFileUpload(email, password, outputDir, resourcesDir, fileName); } catch (Exception ex) { responseObject.flag = false; responseObject.message = "Document import failed"; responseObject.exceptionMsg = ex.Message; } return(responseObject); }
public IHttpActionResult PostPhoto() { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } int iUploadedCnt = 0; // DEFINE THE PATH WHERE WE WANT TO SAVE THE FILES. string sPath = ""; string sColoredPath = ""; string unicalCode = ""; string fileName = ""; sPath = System.Web.Hosting.HostingEnvironment.MapPath("~/photos/xrayoriginal/"); sColoredPath = System.Web.Hosting.HostingEnvironment.MapPath("~/photos/xraycolored/"); unicalCode = Guid.NewGuid().ToString(); System.Web.HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files; // CHECK THE FILE COUNT. if (hfc.Count == 1) { System.Web.HttpPostedFile hpf = hfc[0]; string description = HttpContext.Current.Request.Params.Get("desc"); string name = HttpContext.Current.Request.Params.Get("name"); string x = HttpContext.Current.Request.Params.Get("patientId"); int patientId = Int32.Parse(x); if (hpf.ContentLength > 0) { fileName = unicalCode + hpf.FileName; // CHECK IF THE SELECTED FILE(S) ALREADY EXISTS IN FOLDER. (AVOID DUPLICATE) if (!File.Exists(sPath + Path.GetFileName(fileName))) { // SAVE THE FILES IN THE FOLDER. hpf.SaveAs(sPath + Path.GetFileName(fileName)); iUploadedCnt = iUploadedCnt + 1; } string filePath = sPath + Path.GetFileName(fileName); ColorChanger algorithm = new ColorChanger(filePath); algorithm.ColorImage(); algorithm.SaveColoredImage(sColoredPath + "colored" + fileName); var image = new Photo { DiseaseName = name, DiseaseDescription = description, XrayPhotoBlobSource = "/photos/xrayoriginal/" + Path.GetFileName(fileName), ColoredPhotoBlobSource = "/photos/xraycolored/" + "colored" + Path.GetFileName(fileName), IsColored = true, Patient = db.Patients.Single(p => p.Id == patientId) }; db.Photos.Add(image); db.SaveChanges(); var patients = db.Patients.Single(p => p.Id == patientId); if (patients != null) { patients.Photos.Add(image); db.SaveChanges(); } return(Ok($@"http:\\{Request.RequestUri.Host}\photos\xrayoriginal\{fileName}")); } } return(BadRequest("Upload Failed")); }
public ActionResult AddImage(HttpPostedFile uploadFile, int eventID) { string[] all = Request.Files.AllKeys; foreach (string file in Request.Files.AllKeys) { HttpPostedFileBase hpf = Request.Files[file]; if (hpf.ContentLength == 0) continue; else { var fileName = DateTime.Now.Ticks + Path.GetFileName(hpf.FileName); var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "Images/uploads/", fileName); uploadFile.SaveAs(path); } } ViewData["UploadSucceed"] = "Image upload succeded"; return RedirectToAction("ShowImages", new { eventID = eventID }); //if (uploadFile.ContentLength > 0) //{ // var fileName = DateTime.Now.Ticks + Path.GetFileName(uploadFile.FileName); // var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "Images/uploads/", fileName); // uploadFile.SaveAs(path); // ViewData["UploadSucceed"] = "Image upload succeded"; // return RedirectToAction("ShowImages", new { eventID = eventID }); //} //else //{ // ViewBag.UploadError = ""; // return View(); //} }
public static string Up(HttpPostedFile file) { string lfilename = file.FileName; string lfilepath = Root + lfilename; file.SaveAs(lfilepath); return lfilepath; }