public void Unload(HttpResponseBase Response, HttpServerUtilityBase Server) { Response.ContentType = "application/xml"; Response.AppendHeader("Content-Disposition", "attachment; filename=peoples.xml"); Response.TransmitFile(Server.MapPath("~/files/peoples.xml")); Response.End(); }
/// <summary> /// 将文件写入响应流,根据请求标头和文件属性添加正确的标头 /// </summary> /// <param name="response"></param> protected virtual void TransmitFile(HttpResponseBase response) { var contentLength = ContentLength(); response.StatusCode = SendRange() ? (int)HttpStatusCode.PartialContent : (int)HttpStatusCode.OK; response.AppendHeader(HttpHeaders.ContentLength, contentLength.ToString(CultureInfo.InvariantCulture)); response.AppendHeader(HttpHeaders.AcceptRanges, "bytes"); response.AppendHeader(HttpHeaders.ContentRange, $"bytes {_byteRange.Start}-{_byteRange.End}/{_file.Length}"); response.AppendHeader(HttpHeaders.AccessControlExposeHeaders, HttpHeaders.ContentDisposition); if (!string.IsNullOrWhiteSpace(_downloadFileName)) { response.AddHeader("Content-Disposition", $"attachment;filename=\"{_downloadFileName}\""); } try { response.TransmitFile(FileName, _byteRange.Start, contentLength); } catch (Exception ex) { LogException?.Invoke(ex); } }
private bool TryTransmitIfContains(string id, HttpResponseBase response, string imgFile) { var tmpFiles = Directory.GetFiles(CachePath, id + "_*" + tmpFileExtension); // check if we have cache files if (tmpFiles.Length > 0) { // TODO: Log warning about duplicate cache entries // we expect to find just one file for each ID var tmpFile = tmpFiles [0]; lock (GetFileLockObject(tmpFile)) { // get tmp short filename without extension var tmpFileName = Path.GetFileNameWithoutExtension(Path.GetFileName(tmpFile)); // extract expire time var expireTime = DateTime.MinValue; var timeIndex = tmpFileName.LastIndexOf("_") + 1; if (timeIndex > 0) { expireTime = DateTime.FromFileTime( Convert.ToInt64(tmpFileName.Substring(timeIndex))); } var hitCache = false; if (imgFile == "") { // check if cache is expired hitCache = expireTime >= DateTime.Now; } else if (timeIndex == 0) { // use original file last write time var imgFileInfo = new FileInfo(imgFile); var tmpFileInfo = new FileInfo(tmpFile); hitCache = tmpFileInfo.LastWriteTime > imgFileInfo.LastWriteTime; } if (hitCache) { response.TransmitFile(tmpFile); return(true); } else { File.Delete(tmpFile); return(false); } } } return(false); }
public void DownloadDir(string path) { path = FixPath(path); if (!Directory.Exists(path)) throw new Exception(LangRes("E_CreateArchive")); string dirName = new FileInfo(path).Name; string tmpZip = _context.Server.MapPath("../tmp/" + dirName + ".zip"); if (System.IO.File.Exists(tmpZip)) System.IO.File.Delete(tmpZip); System.IO.Compression.ZipFile.CreateFromDirectory(path, tmpZip, CompressionLevel.Fastest, true); _r.Clear(); _r.Headers.Add("Content-Disposition", "attachment; filename=\"" + dirName + ".zip\""); _r.ContentType = MimeTypes.ApplicationForceDownload; _r.TransmitFile(tmpZip); _r.Flush(); System.IO.File.Delete(tmpZip); _r.End(); }
public override void ExecuteResult(ControllerContext context) { HttpResponseBase response = context.HttpContext.Response; response.Buffer = false; response.ContentType = _contentType; response.AddHeader("Content-Disposition", "attachment; filename=" + _filenameWithExtension); // force download response.AddHeader("X-Content-Type-Options", "nosniff"); response.TransmitFile(_filePath); }
protected override void WriteFile(HttpResponseBase response) { response.Clear(); response.AppendHeader("content-disposition", "attachment; filename=" + _fName); response.ContentType = "application/octet-stream;charset=utf-8"; response.TransmitFile(_fileSystemPath); //response.WriteFile(_fileSystemPath); //byte[] buffer = System.IO.File.ReadAllBytes(_fileSystemPath); //string check = Encoding.UTF8.GetString(buffer); //response.BinaryWrite(buffer); }
/// <summary> /// Writes content of the <paramref name="filePath"/> to the HTTP response, ensuring that valid content (MIME) type is specified. /// </summary> /// <param name="response">HTTP response.</param> /// <param name="path">Path to the file whose content will be written to the response.</param> public static void TransmitFileContent(this HttpResponseBase response, string filePath) { string filename = Path.GetFileName(filePath); if (filename == null) { return; } response.ContentType = MimeMapping.GetMimeMapping(filename); response.TransmitFile(filePath); }
public void DownloadDir(string path) { path = FixPath(path); if (!Directory.Exists(path)) { throw new Exception(LangRes("E_CreateArchive")); } string dirName = new FileInfo(path).Name; string tmpZip = _context.Server.MapPath("~/Content/Roxy_Fileman/temp/" + dirName + ".zip"); if (System.IO.File.Exists(tmpZip)) { System.IO.File.Delete(tmpZip); } ZipFile.CreateFromDirectory(path, tmpZip, CompressionLevel.Fastest, true); _response.Clear(); _response.Headers.Add("Content-Disposition", "attachment; filename=\"" + dirName + ".zip\""); _response.ContentType = "application/force-download"; _response.TransmitFile(tmpZip); _response.Flush(); System.IO.File.Delete(tmpZip); _response.End(); }
public virtual bool SendContent(string url, HttpResponseBase response) { var file = GetFileNameFromConfig(url); try { response.TransmitFile(file); RRTracer.Trace("{0} transmitted from disk.", url); return(true); } catch (FileNotFoundException) { try { response.TransmitFile(file.Insert(file.LastIndexOf('-'), "-Expired")); RRTracer.Trace("{0} was expired and transmitted from disk.", url); return(true); } catch (FileNotFoundException) { return(false); } } }
public override void ExecuteResult(ControllerContext context) { HttpResponseBase response = context.HttpContext.Response; FileInfo info = new FileInfo(this.fileName); bool isPartial = hasValidRange && !(from == 0 && (to == info.Length - 1 || !to.HasValue)); response.StatusCode = isPartial ? 206 : 200; response.ContentType = mediaType; response.Headers.Add("Accept-Ranges", "bytes"); if (isPartial) { long end = to.HasValue ? to.Value : info.Length - 1, count = end + 1 - from.Value; response.Headers.Add("Content-Range", $"bytes {from}-{end}/{info.Length}"); response.TransmitFile(this.fileName, from.Value, count); } else { response.TransmitFile(this.fileName); } }
public static void RedirectToDownload(string filepath, string contentType, HttpResponseBase response) { FileInfo file = new FileInfo(filepath); if (file.Exists) { response.ClearContent(); response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name); response.AddHeader("Content-Length", file.Length.ToString()); response.ContentType = contentType; response.TransmitFile(file.FullName); response.End(); } else { throw new FileNotFoundException(); } }
private static bool TransmitFileDownload(HttpResponseBase response, string filePath, string fileName, Encoding encoding) { try { return(ExecuteDownload(response, () => { response.TransmitFile(filePath); }, true, filePath, fileName, encoding)); } catch { if (response != null) { response.Close(); } throw; } }
private bool TryTransmitIfContains(string id, HttpResponseBase response) { if (EnableAutoPurge) { QueueAutoPurge(); } string path = BuildFilePath(id); lock (GetFileLockObject(id)) { if (File.Exists(path)) { response.TransmitFile(path); return(true); } return(false); } }
//This is used for times where you have a physical location public override void ExecuteResult(ControllerContext context) { HttpResponseBase response = context.HttpContext.Response; response.Clear(); response.Cache.SetCacheability(HttpCacheability.NoCache); response.ContentType = ContentType; //Check to see if this is done from bytes or physical location // If you're really paranoid you could set a true/false flag in // the constructor. if (ImageBytes != null) { var stream = new MemoryStream(ImageBytes); stream.WriteTo(response.OutputStream); stream.Dispose(); } else { response.TransmitFile(SourceFilename); } }
/// <summary> /// If a range is specified, this will handle it. /// </summary> /// <param name="response"></param> /// <returns></returns> protected virtual bool HandleRange(HttpResponseBase response) { if (!Options.SupportByteRange) { return(false); } response.AddHeader("Accept-Ranges", "bytes"); var request = HttpContext.Current.Request; var range = ParseRange(request.Headers["Range"]); if (range == null) { return(false); } var fi = new FileInfo(FileName); var end = Math.Min(range.End, fi.Length - 1); // last byte is at 1 less than the length (0 based); var length = end - range.Start + 1; // the start is 0 based and end is inclusive. Eg, a range of 0-0 would be 1 byte. var ifrange = request.Headers["If-Range"]; if (ifrange.HasValue()) { if (mETag != ifrange) { return(false); } } response.StatusCode = 206; response.StatusDescription = "Partial Content"; response.AddHeader("Content-Range", "bytes {0}-{1}/{2}".Fmt(range.Start, end, fi.Length)); response.TransmitFile(FileName, range.Start, end); return(true); }
private ActionResult down(string path, string fileName) { string downPath = GetUploadPath(path); if (!System.IO.File.Exists(downPath)) { return(Content("文件不存在!")); } if (CheckImage(downPath)) { return(File(GetImageByte(downPath), @"image/jpeg")); } if (!fileName.Contains(".")) { fileName += Path.GetExtension(downPath); } HttpResponseBase response = this.HttpContext.Response; HttpServerUtilityBase server = this.HttpContext.Server; response.Clear(); response.Buffer = true; if (Request.Browser.Browser == "Firefox") { Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName); } else { Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8)); } response.ContentType = CheckImage(downPath) ? "image/*" : "application/octet-stream"; //response.AppendHeader("Content-Length", "attachment;filename=" + fileName); response.TransmitFile(downPath); response.Flush(); response.Close(); return(null); }
public void Serve(HttpResponseBase response) { response.TransmitFile(FileName); }
protected override void WriteFile(HttpResponseBase response) { response.TransmitFile(FileName); }
protected override void WriteFile(HttpResponseBase response) { var ifNoneMatch = _httpContext.Request.Headers["If-None-Match"]; if (ifNoneMatch.HasValue() && _etag == ifNoneMatch) { // File hasn't changed, so return HTTP 304 without retrieving the data response.StatusCode = (int)HttpStatusCode.NotModified; response.StatusDescription = "Not Modified"; // Explicitly set the Content-Length header so the client doesn't wait for // content but keeps the connection open for other requests response.AddHeader("Content-Length", "0"); ApplyResponseHeaders(response, false); } else { if (_path != null) { response.TransmitFile(_path); } else if (_streamReader != null) { var stream = _streamReader(); if (stream == null) { throw new NullReferenceException("File stream cannot be NULL."); } // Grab chunks of data and write to the output stream var outputStream = response.OutputStream; using (stream) { var buffer = new byte[BufferSize]; while (true) { int bytesRead = stream.Read(buffer, 0, BufferSize); if (bytesRead == 0) { // no more data break; } outputStream.Write(buffer, 0, bytesRead); } } } else if (_bufferReader != null) { var buffer = _bufferReader(); if (buffer == null) { throw new NullReferenceException("File buffer cannot be NULL."); } // Write buffer to output stream response.OutputStream.Write(buffer, 0, buffer.Length); } ApplyResponseHeaders(response, true); // Set ETag for served file (revalidated on subsequent requests) response.Cache.SetETag(_etag); } }
protected override void WriteFile(HttpResponseBase response) { HttpContext context = HttpContext.Current; response.TransmitFile(this.Filename); }
/// <summary> /// Writes the file range to the response. /// </summary> /// <param name="response">The response from context within which the result is executed.</param> /// <param name="rangeStartIndex">Range start index</param> /// <param name="rangeEndIndex">Range end index</param> protected override void WriteEntityRange(HttpResponseBase response, long rangeStartIndex, long rangeEndIndex) { response.TransmitFile(FileName, rangeStartIndex, (rangeEndIndex - rangeStartIndex) + 1); }
public override void TransmitFile(string filename) { proxiedResponse.TransmitFile(filename); }
public override void TransmitFile(string filename) { _httpResponseBase.TransmitFile(filename); }
public void Serve(HttpResponseBase response, long offset, long length) { response.TransmitFile(FileName, offset, length); }