c# 根据下载请求动态重命名文件

发布于 2024-09-06 18:12:42 字数 70 浏览 1 评论 0原文

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

Is it possible to rename file when trying to download it?
For example, I would like to store files to folders using their id's but when user downloads file I'd like to return the original filename.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

阪姬 2024-09-13 18:12:42

只需在此处更改文件名,

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

例如

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

在 ASP 中使用“另存为”对话框下载文件.NET

just change name of file over here

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

for example

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

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

奶气 2024-09-13 18:12:42

名称 = 档案名称 + 扩展名 (ejemplo.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();
}

nombre = nombre del archivo + extension (ejemplo.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();
}
浪菊怪哟 2024-09-13 18:12:42

我正在使用 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 时,能够覆盖 ApiController 的默认行为,正如您所看到的,您可以更改返回流中写入的内容,此外您还可以更改内容配置(在其中设置文件名)。

最后,在此自定义 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;
    }

I am working with an API controller in C# and the return of my request needed to be IHttpActionResult

After several research hours, here is my solution.

As a return for my request, I'm using Content method from ApiController.cs :

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

I had to create a custom MediaTypeFormatter which is :

class PdfMediaTypeFormatter : BufferedMediaTypeFormatter
{
    private const string ContentType = "application/pdf";
    private string FileName { get; set; }
    public PdfMediaTypeFormatter(byte[] doc)
    {
        FileName = 
quot;{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;
    }
}

And the method in the controller looks like this :

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

For the explanation, this ables to override the default behavior of ApiController when it has to return an HttpRequest, as you can see you are able to change what is written is the returned stream, besides you're able to change content disposition, where you set the file name.

Finally, in the constructor of this custom MediaTypeFormatter, I retrieve the Title of the document using a method in a static utils class, which is :

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;
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文