protected override void OnLoad(EventArgs e) { try { base.OnLoad(e); // Response.Buffer = true; // Response.BufferOutput = true; Response.Clear(); Response.ClearHeaders(); Response.Buffer = false; SysAttachment obj = this.GetAttachment(); // 解决文件名乱码问题。 string Original_File_Name = System.Web.HttpUtility.UrlEncode(obj.OriginalFileName, System.Text.Encoding.UTF8); this.Response.ContentType = obj.ContentType; this.Response.AddHeader("Content-Disposition", "attachment;filename=" + Original_File_Name); this.Response.AddHeader("Content-Length", obj.FileSize.ToString()); string file_path = this.GetFilePath(obj); this.Response.WriteFile(file_path); //this.Response.End(); System.Web.HttpContext.Current.ApplicationInstance.CompleteRequest(); } catch (Exception ex) { SimpleFlow.SystemFramework.Log.WriteLog(ex); this.Response.Redirect("~/Communication.aspx"); } }
/// <summary> /// 将上传文件加到某个批次 /// </summary> /// <param name="curr_user"></param> /// <param name="postedFile"></param> /// <param name="batch_id"></param> /// <returns></returns> public static SysAttachment InsertAttachment(SysAttachment item, SysBatchUpload batch_entity) { SqlConnection conn = new SqlConnection(Config.ConnectionString); conn.Open(); try { SqlTransaction trans = conn.BeginTransaction(); try { SqlHelper.Insert(trans, item); SqlHelper.Insert(trans, batch_entity); trans.Commit(); } catch (Exception ex) { trans.Rollback(); throw ex; } } finally { conn.Close(); } return(item); }
protected void btnUpload_Click(object sender, EventArgs e) { if ((updFile.PostedFile != null) && (!string.IsNullOrEmpty(updFile.PostedFile.FileName))) { SysAttachment item = AttachmentBiz.InsertAttachment(this.GetCurrentUserInfo(), updFile.PostedFile); List <SysAttachment> attachList = new List <SysAttachment>(); if (this.ViewState["Attachments"] != null) { attachList.AddRange(this.ViewState["Attachments"] as SysAttachment[]); } attachList.Add(item); this.ViewState["Attachments"] = attachList.ToArray(); this.GridView1.DataSource = attachList; this.GridView1.DataBind(); this.txtFileList.Value = this.AttachmentList2String(attachList); if (this.txtAllowMoreFiles.Value != "Y") { this.txtCloseOnLoad.Value = "Y"; } } }
private string GetFilePath(SysAttachment obj) { string base_dir = AttachmentBiz.GetDocPath(obj.PathId); string file_dir = System.IO.Path.Combine(base_dir, obj.CurrentFileDir); string file_path = System.IO.Path.Combine(file_dir, obj.CurrentFileName); return(file_path); }
public List <SysAttachment> GetAttachments() { List <SysAttachment> list = new List <SysAttachment>(); SysAttachment item = AttachmentBiz.GetAttachment(this.AttachmentID); list.Add(item); return(list); }
private void insert_one_file(FileUpload file_upload, SysUserInfo curr_user, string batch_id) { if ((file_upload.PostedFile != null) && (!string.IsNullOrEmpty(file_upload.PostedFile.FileName))) { SysAttachment attachment = AttachmentBiz.InsertAttachment(curr_user, file_upload.PostedFile, batch_id); } }
/// <summary> /// 将上传文件加到某个批次 /// </summary> /// <param name="curr_user"></param> /// <param name="postedFile"></param> /// <param name="batch_id"></param> /// <returns></returns> public static SysAttachment InsertAttachment(SysUserInfo curr_user, System.Web.HttpPostedFile postedFile, string batch_id) { string originalFilePath = postedFile.FileName; // save file // get user's site SysSiteList site_entity = AttachmentDataAccess.GetSysSiteList(curr_user.SiteSerial); if (site_entity == null) { throw new ApplicationException(string.Format("site [{0}] does not exists.", curr_user.SiteSerial)); } // get site's upload path SysDocPath doc_path_entity = AttachmentDataAccess.GetSysDocPath(site_entity.CurrentUploadPathId); if (doc_path_entity == null) { throw new ApplicationException(string.Format("path_id [{0}]does not configed in db.", site_entity.CurrentUploadPathId)); } string baseDir = doc_path_entity.DocPath; // get child dir DateTime dt_now = DateTime.Now; string subDir = dt_now.ToString("yyyyMM"); string fileDir = Path.Combine(baseDir, subDir); if (!System.IO.Directory.Exists(fileDir)) { System.IO.Directory.CreateDirectory(fileDir); } string attachmentId = System.Guid.NewGuid().ToString("D"); string currentFileName = attachmentId + Path.GetExtension(originalFilePath); string currentFilePath = Path.Combine(fileDir, currentFileName); postedFile.SaveAs(currentFilePath); SysAttachment item = new SysAttachment(); item.AttachmentId = attachmentId; item.CurrentFileName = currentFileName; item.CurrentFileDir = subDir; item.FileSize = postedFile.ContentLength; // postedFile. item.OriginalFileName = Path.GetFileName(originalFilePath); item.UploadTime = dt_now; item.UploadUser = curr_user.UserId; item.ContentType = postedFile.ContentType; item.PathId = site_entity.CurrentUploadPathId; item.FileExtension = Path.GetExtension(originalFilePath); SysBatchUpload batch_entity = new SysBatchUpload(batch_id, attachmentId); AttachmentDataAccess.InsertAttachment(item, batch_entity); return(item); }
/// <summary> /// 删除批次中的某个文件 /// </summary> /// <param name="batch_id"></param> /// <param name="attachment_id"></param> public static void DeleteBatchAttachment(string batch_id, string attachment_id) { List <string> file_list = new List <string>(1); SqlConnection conn = new SqlConnection(Config.ConnectionString); conn.Open(); try { SqlTransaction trans = conn.BeginTransaction(); try { SysAttachment attr = SqlHelper.Retrieve(trans, new SysAttachment(attachment_id)); if (attr != null) { file_list.Add(GetFilePath(attr)); SqlHelper.Delete(trans, attr); } SqlHelper.Delete(trans, new SysBatchUpload(batch_id, attachment_id)); trans.Commit(); } catch (Exception ex) { trans.Rollback(); throw ex; } } finally { conn.Close(); } foreach (string file_path in file_list) { try { System.IO.File.Delete(file_path); } catch (Exception ex) { SimpleFlow.SystemFramework.Log.WriteLog(ex); } } }
private string AttachmentList2String(List <SysAttachment> attachList) { StringBuilder sb = new StringBuilder(100); for (int i = 0; i < attachList.Count; i++) { SysAttachment obj = attachList[i]; if (i > 0) { sb.Append(";"); } sb.Append(Microsoft.JScript.GlobalObject.escape(obj.AttachmentId)); sb.Append("="); sb.Append(Microsoft.JScript.GlobalObject.escape(obj.OriginalFileName)); } return(sb.ToString()); }
public ActionResult SaveData(string RelationID, List <SysAttachment> files) { try { if (string.IsNullOrEmpty(RelationID)) { return(Json(new { Code = 1, Msg = "保存失败,关联ID不能为空" })); } //先删除 var models = dbContext.SysAttachment.Where(x => x.RelationId == RelationID); if (models != null) { dbContext.SysAttachment.RemoveRange(models); } dbContext.SaveChanges(); if (files == null || files.Count == 0) { return(Json(new { Code = 0, Msg = "保存成功" })); } var users = dbContext.SysUser.ToList(); //后添加 for (int i = 0; i < files.Count; i++) { SysAttachment model = files[i]; model.RelationId = RelationID; model.Status = 0; model.Size = 0; model.CreateBy = string.IsNullOrEmpty(model.CreateBy) ? Convert.ToString(SSOClient.UserId) : model.CreateBy; model.CreateByName = users.FirstOrDefault(t => t.UserId.ToString() == model.CreateBy).UserName; dbContext.SysAttachment.Add(model); } dbContext.SaveChanges(); return(Json(new { Code = 0, Msg = "保存成功", Data = files })); } catch (Exception ex) { LogHelper.SaveLog(ex); return(Json(new { Code = 1, Msg = "服务器异常,请联系管理员!" })); } }
public async System.Threading.Tasks.Task <JsonResult> Upload() { try { IFormFile file = Request.Form.Files[0]; Guid fileId = Guid.NewGuid(); DateTime nowDate = DateTime.Now; string path = string.Format("/UploadFiles/{0:yyyyMMdd}/{1}", nowDate, fileId); string url = string.Format("{0}/{1}", path, file.FileName); // 服务器的存储全路径 string destFileName = MapPath(url); // 创建目录路径 if (!Directory.Exists(Path.GetDirectoryName(destFileName))) { Directory.CreateDirectory(Path.GetDirectoryName(destFileName)); } SysAttachment fileData = new SysAttachment(); fileData.Id = fileId; //fileDatas.RelationID = ""; fileData.Name = file.FileName; fileData.Names = ""; fileData.Url = url; fileData.Type = 0; fileData.Suffix = Path.GetExtension(file.FileName).ToLower(); fileData.Path = path; fileData.Status = 0; fileData.Size = 0; fileData.CreateBy = ""; fileData.CreateByName = SSOClient.User.UserName; fileData.CreateTime = nowDate; using (var stream = System.IO.File.Create(destFileName)) { await file.CopyToAsync(stream); } // 图片文件扩展名验证正则表达式 Regex regexExtension = new Regex(@".*\.(jpg|jpeg|png|gif|bmp)"); if (regexExtension.IsMatch(destFileName.ToLower())) { string ThumbnailSizes = Request.Form["thumbnailSizes"].FirstOrDefault(); string[] ThumbnailSizeArr = new string[] { }; //生成缩略图 if (!string.IsNullOrEmpty(ThumbnailSizes) && (ThumbnailSizeArr = ThumbnailSizes.Split(';')).Length > 0) { string[] fileNamesArr = new string[ThumbnailSizeArr.Length]; for (int i = 0; i < ThumbnailSizeArr.Length; i++) { string size = ThumbnailSizeArr[i]; string ThumbFileName = Path.GetFileNameWithoutExtension(url) + "_" + size + fileData.Suffix; string ThumbPath = url.Replace(Path.GetFileName(url), ThumbFileName); ThumbnailHelper.MakeThumbnail(Convert.ToInt32(size), MapPath(url), MapPath(ThumbPath)); fileNamesArr[i] = ThumbFileName; } fileData.Names = string.Join("|", fileNamesArr); } } return(Json(new { Code = 0, Msg = "", Data = fileData })); } catch (Exception ex) { LogHelper.SaveLog(ex); return(Json(new { Code = 1, Msg = "服务器异常,请联系管理员!" })); } }
public async Task <JsonResult> Upload() { try { IFormFile file = Request.Form.Files[0]; Guid fileId = Guid.NewGuid(); DateTime nowDate = DateTime.Now; string path = string.Format("/uploadfiles/{0:yyyy/MMdd}/{1}", nowDate, fileId); string url = string.Format("{0}/{1}", path, file.FileName); // 服务器的存储全路径 string destFileName = MapPath(url); // 创建目录路径 if (!Directory.Exists(Path.GetDirectoryName(destFileName))) { Directory.CreateDirectory(Path.GetDirectoryName(destFileName)); } SysAttachment fileData = new SysAttachment(); fileData.Id = fileId; //fileDatas.RelationID = ""; fileData.Name = file.FileName; fileData.Names = ""; fileData.Url = url; fileData.Type = 0; fileData.Suffix = Path.GetExtension(file.FileName).ToLower(); fileData.Path = path; fileData.Status = 0; fileData.Size = 0; fileData.CreateBy = ""; fileData.CreateByName = SSOClient.User.UserName; fileData.CreateTime = nowDate; string ThumbnailSizes = Request.Form["thumbnailSizes"].FirstOrDefault(); if (string.IsNullOrEmpty(FileServiceUrl)) { //保存本地 using (var stream = System.IO.File.Create(destFileName)) { await file.CopyToAsync(stream); } // 图片文件扩展名验证正则表达式 Regex regexExtension = new Regex(@".*\.(jpg|jpeg|png|gif|bmp)"); if (regexExtension.IsMatch(destFileName.ToLower())) { string[] ThumbnailSizeArr = new string[] { }; //生成缩略图 if (!string.IsNullOrEmpty(ThumbnailSizes) && (ThumbnailSizeArr = ThumbnailSizes.Split(';')).Length > 0) { string[] fileNamesArr = new string[ThumbnailSizeArr.Length]; for (int i = 0; i < ThumbnailSizeArr.Length; i++) { string size = ThumbnailSizeArr[i]; string ThumbFileName = Path.GetFileNameWithoutExtension(url) + "_" + size + fileData.Suffix; string ThumbPath = url.Replace(Path.GetFileName(url), ThumbFileName); ThumbnailHelper.MakeThumbnail(Convert.ToInt32(size), MapPath(url), MapPath(ThumbPath)); fileNamesArr[i] = ThumbFileName; } fileData.Names = string.Join("|", fileNamesArr); } } } else { //保存文件服务器 HttpClient client = new HttpClient(); MultipartFormDataContent form = new MultipartFormDataContent(); byte[] uploadFileBytes = new byte[file.Length]; file.OpenReadStream().Read(uploadFileBytes, 0, (int)file.Length); MemoryStream stream = new MemoryStream(uploadFileBytes); StreamContent fileContent = new StreamContent(stream); fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data"); fileContent.Headers.ContentDisposition.FileName = url; form.Add(fileContent); StringContent thumbnailSizes = new StringContent(ThumbnailSizes); thumbnailSizes.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data"); thumbnailSizes.Headers.ContentDisposition.Name = "thumbnailSizes"; form.Add(thumbnailSizes); HttpResponseMessage res = client.PostAsync(FileServiceUrl, form).Result; var json = res.Content.ReadAsStringAsync().Result; JObject result = JObject.Parse(json); fileData.Path = (string)result["data"]["path"]; fileData.Names = (string)result["data"]["names"]; fileData.Url = (string)result["data"]["url"]; } return(Json(new { Code = 0, Msg = "", Data = fileData })); } catch (Exception ex) { LogHelper.SaveLog(ex); return(Json(new { Code = 1, Msg = "服务器异常,请联系管理员!" })); } }
public static void InsertAttachment(SysAttachment item) { SqlHelper.Insert(Config.ConnectionString, item); }
private static string GetFilePath(SysAttachment att) { string dir = System.IO.Path.Combine(GetDocPath(att.PathId), att.CurrentFileDir); return(System.IO.Path.Combine(dir, att.CurrentFileName)); }
internal static void InsertAttachment(SysAttachment item) { AttachmentDataAccess.InsertAttachment(item); }