/// <summary> /// Saves the posted file to disk and adds its mimetype /// to the mimetype manager if it does not exist already /// </summary> private static void SavePostedFile(BinaryFile file, string path) { file.SaveAs(path); m_Logger.DebugFormat("File '{0}' saved to '{1}'", file.FileName, path); MimeTypeManager.AddMimeType(file.FileExtension, file.ContentType); }
/// <summary> /// Writes the specified file to the response stream with the specified filename. /// If forceDownload is true, the download will force a download box in the user's browser /// </summary> protected void WriteFileToResponseStream(string path, string downloadFilename, bool forceDownload) { string extension = Path.GetExtension(path); string contentType = (forceDownload) ? m_ForceDownloadMimeType : MimeTypeManager.GetMimeType(extension); WriteFileToResponseStream(path, downloadFilename, contentType); }
protected void UploadButton_Click(object sender, EventArgs e) { if (FileUpload1.HasFile) { MimeTypeManager.AddMimeType(Path.GetExtension(FileUpload1.PostedFile.FileName), FileUpload1.PostedFile.ContentType); } Response.Redirect("ViewMimeTypes.aspx"); }
public static void SendFile(string filename, byte[] bytes, bool forceDownload) { string downloadFilename = filename; // Workaround for problem in IE6 where it appends [1] onto filenames containing periods if (HttpContext.Current.Request.Browser.Browser == "IE") { string f = (Path.GetFileNameWithoutExtension(downloadFilename) ?? string.Empty); string f2 = f.Replace(".", "%2e"); downloadFilename = downloadFilename.Replace(f, f2); } // Wrap it in quotes to keep spaces downloadFilename = string.Format("\"{0}\"", downloadFilename); // Set content type and disposition string contentType = MimeTypeManager.GetMimeType(Path.GetExtension(filename)); string contentDisposition = string.Format("filename={0}", downloadFilename); if (forceDownload) { contentDisposition = "attachment;" + contentDisposition; } // Set the headers HttpContext.Current.Response.ContentType = contentType; HttpContext.Current.Response.AppendHeader("Content-Disposition", contentDisposition); HttpContext.Current.Response.AppendHeader("Content-Length", bytes.Length.ToString()); // Send the file if (HttpContext.Current.Response.IsClientConnected) { HttpContext.Current.Response.BinaryWrite(bytes); } HttpContext.Current.Response.End(); }
protected void btnPost_Click(object sender, EventArgs e) { if (action == OperateType.Edit) { int id = int.Parse(Request.QueryString["ID"]); ArticleAttachment attachment = ArticleAttachments.GetAttachment(id); attachment.Name = txtTitle.Text; attachment.Desc = txtMemo.Text; attachment.IsRemote = cboAttachmentType.SelectedIndex == 1; attachment.Memo = txtMemo.Text; attachment.Status = csAttachment.SelectedValue; // 判断是远程则直接更新URL,否则先删除本地文件 if (cboAttachmentType.SelectedIndex == 1) { // 远程 attachment.IsRemote = true; // TODO: 删除文件 string filePath = attachmentLocalPath + attachment.FileName; File.Delete(filePath); // 更新字段 attachment.FileName = txtUrl.Text; } else { // 本地上传 attachment.IsRemote = false; // TODO: 本地上传 // 获取扩展名 string ext = Path.GetExtension(fuLocal.FileName); attachment.FileName = Guid.NewGuid().ToString() + ext; string filePath = attachmentLocalPath + attachment.FileName; fuLocal.SaveAs(filePath); } attachment.ContentType = MimeTypeManager.GetMimeType(attachment.FileName); attachment.UpdateTime = DateTime.Now; attachment.UpdateUser = Profile.AccountInfo.UserID; DataActionStatus status = ArticleAttachments.UpdateArticleAttachment(attachment); if (status == DataActionStatus.DuplicateName) { mbMsg.ShowMsg("修改附件失败,存在同名附件!"); } else if (status == DataActionStatus.UnknownFailure) { throw new HHException(ExceptionType.Failed, "更新附件信息失败,请联系管理员!"); } else if (status == DataActionStatus.Success) { throw new HHException(ExceptionType.Success, "操作成功,已成功更新附件!"); } } else { ArticleAttachment attachment = new ArticleAttachment(); attachment.Name = txtTitle.Text; attachment.Desc = txtMemo.Text; attachment.IsRemote = cboAttachmentType.SelectedIndex == 1; attachment.Memo = txtMemo.Text; attachment.Status = csAttachment.SelectedValue; // 判断是远程则直接更新URL if (cboAttachmentType.SelectedIndex == 1) { // 远程 attachment.IsRemote = true; // url字段 attachment.FileName = txtUrl.Text; } else { // 本地上传 attachment.IsRemote = false; // TODO: 本地上传 string ext = Path.GetExtension(fuLocal.FileName); attachment.FileName = Guid.NewGuid().ToString() + ext; string filePath = attachmentLocalPath + attachment.FileName; fuLocal.SaveAs(filePath); } attachment.ContentType = MimeTypeManager.GetMimeType(attachment.FileName); attachment.CreateTime = DateTime.Now; attachment.CreateUser = Profile.AccountInfo.UserID; attachment.UpdateTime = DateTime.Now; attachment.UpdateUser = Profile.AccountInfo.UserID; DataActionStatus status; ArticleAttachments.AddArticleAttachment(attachment, out status); if (status == DataActionStatus.DuplicateName) { throw new HHException(ExceptionType.Failed, "新增附件失败,存在同名附件!"); } else if (status == DataActionStatus.UnknownFailure) { throw new HHException(ExceptionType.Failed, "新增附件失败,请联系管理员!"); } else if (status == DataActionStatus.Success) { throw new HHException(ExceptionType.Success, "操作成功,已成功增加一个新的附件!"); } } }
public void ProcessRequest(HttpContext context) { FileSystemStorageFile file = FileStorageProvider.GetStorageFileByUrl(context.Request.Path) as FileSystemStorageFile; if (file == null) { //文件未找到 context.Response.StatusCode = 404; return; } DateTime lastModified = (new FileInfo(file.FullLocalPath)).LastWriteTime; DateTime currentLastModifiedDate = DateTime.MinValue; //文件未被修改过 DateTime.TryParse(context.Request.Headers["If-Modified-Since"] ?? "", out currentLastModifiedDate); if (Math.Abs(((TimeSpan)lastModified.ToUniversalTime().Subtract(currentLastModifiedDate.ToUniversalTime())).TotalSeconds) <= 1) { context.Response.StatusCode = 304; context.Response.Status = "304 Not Modified"; return; } long eTag = 0; if (long.TryParse(context.Request.Headers["If-None-Match"] ?? "", out eTag)) { currentLastModifiedDate = new DateTime(eTag); if (lastModified == currentLastModifiedDate) { context.Response.StatusCode = 304; context.Response.Status = "304 Not Modified"; return; } } //设置客户端设置 context.Response.ContentType = MimeTypeManager.GetMimeType(file.FileName); context.Response.Cache.SetAllowResponseInBrowserHistory(true); context.Response.Cache.SetLastModified(lastModified.ToUniversalTime()); context.Response.Cache.SetETag(lastModified.Ticks.ToString()); string disposition; if (context.Response.ContentType == "application/pdf" || context.Response.ContentType == "application/octet-stream") { disposition = "attachment"; } else { disposition = "inline"; } //设置文件名称 if (context.Request.Browser.Browser.IndexOf("Netscape") != -1) { context.Response.AddHeader("Content-disposition", disposition + "; filename*0*=" + context.Server.UrlEncode(GlobalSettings.UrlDecodeFileComponent(file.FileName)).Replace("+", "%20") + ""); } else { context.Response.AddHeader("Content-disposition", disposition + "; filename=" + context.Server.UrlEncode(GlobalSettings.UrlDecodeFileComponent(file.FileName)).Replace("+", "%20") + ""); } if (!file.FullLocalPath.StartsWith(@"\")) { context.Response.TransmitFile(file.FullLocalPath); } else { context.Response.AddHeader("Content-Length", file.ContentLength.ToString("0")); context.Response.Buffer = false; context.Response.BufferOutput = false; using (Stream s = new FileStream(file.FullLocalPath, FileMode.Open, FileAccess.Read)) { byte[] buffer = new byte[64 * 1024]; int read; while ((read = s.Read(buffer, 0, buffer.Length)) > 0) { if (!context.Response.IsClientConnected) { break; } context.Response.OutputStream.Write(buffer, 0, read); context.Response.OutputStream.Flush(); } context.Response.OutputStream.Flush(); context.Response.Flush(); context.Response.Close(); s.Close(); } } }