【问题标题】:c# dynamically rename file upon download requestc#根据下载请求动态重命名文件
【发布时间】:2011-03-06 07:15:00
【问题描述】:

尝试下载文件时是否可以重命名文件? 例如,我想使用他们的 id 将文件存储到文件夹中,但是当用户下载文件时,我想返回原始文件名。

【问题讨论】:

  • 您能否提供更多细节,特别是如何将文件下载到客户端?
  • 您需要在此处提供很多更多信息。什么是下载文件,从什么下载?你的代码适合哪里?
  • 你需要有一个原始名称的存储。
  • @Coding Gorilla...嗯,我没有任何具体的解决方案,我愿意接受建议。我想为他提供一些链接,该链接将返回带有原始文件名的文件(位置)
  • 您的文件是如何存储的?您是从数据库中检索它,还是存储在文件系统中?

标签: c# file download rename


【解决方案1】:

这里改一下文件名

Response.AppendHeader("Content-Disposition","attachment; filename=LeftCorner.jpg");

例如

 string filename = "orignal file name.ext";
 Response.AppendHeader("Content-Disposition","attachment; filename="+ filename  +"");

Downloading a File with a Save As Dialog in ASP.NET

【讨论】:

  • 检查答案中粘贴的链接
  • @ile:没关系。您可以使用: Response.BinaryWrite(fileContent);奖励。您必须在编写任何 Response 之前调用 Response.AppendHeader ,否则它将不起作用。您还应该首先设置 mime-type:Response.ContentType="text/html";
  • 好的,谢谢,我试试。顺便说一句,文件存储在数据库中还是文件系统中都没有关系? (我的情况是文件系统)
【解决方案2】:

名词=档案名称+扩展名(ejemlo.txt)

public void DownloadFile(string ubicacion, string nombre)
{
        Response.Clear();
        Response.ContentType = @"application\octet-stream";
        System.IO.FileInfo file = new System.IO.FileInfo(ubicacion);
        Response.AddHeader("Content-Disposition", "attachment; filename=" + nombre);
        Response.AddHeader("Content-Length", file.Length.ToString());
        Response.ContentType = "application/octet-stream";
        Response.WriteFile(file.FullName);
        Response.Flush();
}

【讨论】:

  • 请添加一些描述您的代码功能的 cmets;请使用英语。最好的问候。
【解决方案3】:

我正在使用 C# 中的 API 控制器,我的请求需要返回 IHttpActionResult

经过几个小时的研究,这是我的解决方案。

作为对我请求的回报,我正在使用来自 ApiController.cs 的 Content 方法:

protected internal FormattedContentResult<T> Content<T>(HttpStatusCode statusCode, T value, MediaTypeFormatter formatter);

我必须创建一个自定义 MediaTypeFormatter,它是:

class PdfMediaTypeFormatter : BufferedMediaTypeFormatter
{
    private const string ContentType = "application/pdf";
    private string FileName { get; set; }
    public PdfMediaTypeFormatter(byte[] doc)
    {
        FileName = $"{DocumentsUtils.GetHeader(doc)}.pdf";
        SupportedMediaTypes.Add(new MediaTypeHeaderValue(ContentType));
    }

    public override bool CanReadType(Type type)
    {
        return type.IsAssignableFrom(typeof(byte[]));
    }

    public override bool CanWriteType(Type type)
    {
        return type.IsAssignableFrom(typeof(byte[]));
    }

    public override void WriteToStream(Type type, object value, Stream writeStream, HttpContent content)
    {

        byte[] doc = (byte[])value;

        using (Stream ms = new MemoryStream())
        {
            byte[] buffer = doc;

            ms.Position = 0;
            ms.Read(buffer, 0, buffer.Length);

            writeStream.Write(buffer, 0, buffer.Length);
        }
    }

    public override void SetDefaultContentHeaders(Type type, HttpContentHeaders headers, MediaTypeHeaderValue mediaType)
    {
        headers.ContentType = new MediaTypeHeaderValue(ContentType);
        headers.ContentDisposition = new ContentDispositionHeaderValue("inline");
        headers.ContentDisposition.FileName = FileName;
    }
}

控制器中的方法如下所示:

public IHttpActionResult GetDownloadedDocument([FromUri] [FromUri] string IdDocument)
    {
        byte[] document = service.GetDoc(IdDocument);
        return Content(HttpStatusCode.OK, document, new PdfMediaTypeFormatter(document));
    }

为了解释,当 ApiController 必须返回一个 HttpRequest 时,它能够覆盖默认行为,正如您所看到的,您可以更改返回的流所写的内容,此外您还可以更改内容配置, 在这里设置文件名。

最后,在这个自定义 MediaTypeFormatter 的构造函数中,我使用静态 utils 类中的方法检索文档的标题,即:

public static string GetHeader(byte[] src)
    {
        if (src.Length > 0)
            using (PdfReader reader = new PdfReader(src))
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    using (PdfStamper stamper = new PdfStamper(reader, ms))
                    {
                        Dictionary<string, string> info = reader.Info;
                        if (!info.Keys.Contains("Title"))
                            return null;
                        else
                            return info["Title"];
                    }
                }
            }
        else
            return null;
    }

【讨论】:

    猜你喜欢
    • 2017-10-20
    • 2013-06-19
    • 2013-02-14
    • 2018-02-26
    • 2014-09-10
    • 2021-11-21
    • 1970-01-01
    • 2015-02-01
    • 2016-03-29
    相关资源
    最近更新 更多