Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/260.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
c#根据下载请求动态重命名文件_C#_File_Download_Rename - Fatal编程技术网

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

c#根据下载请求动态重命名文件,c#,file,download,rename,C#,File,Download,Rename,尝试下载文件时是否可以重命名该文件? 例如,我希望使用文件id将文件存储到文件夹中,但当用户下载文件时,我希望返回原始文件名。只需在此处更改文件名即可 Response.AppendHeader("Content-Disposition","attachment; filename=LeftCorner.jpg"); 比如说 string filename = "orignal file name.ext"; Response.AppendHeader("Content-Dispositi

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

只需在此处更改文件名即可

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

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

nombre=nombre del archivo+扩展名(ejempo.txt)


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

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

作为对我请求的回报,我使用ApiController.cs中的
Content
方法:

protected internal FormattedContentResult<T> Content<T>(HttpStatusCode statusCode, T value, MediaTypeFormatter formatter);
控制器中的方法如下所示:

public IHttpActionResult GetDownloadedDocument([FromUri] [FromUri] string IdDocument)
    {
        byte[] document = service.GetDoc(IdDocument);
        return Content(HttpStatusCode.OK, document, new PdfMediaTypeFormatter(document));
    }
为了便于解释,当ApiController必须返回HttpRequest时,这可以覆盖它的默认行为,正如您可以看到的那样,您可以更改写入的内容是返回的流,此外,您还可以更改设置文件名的内容配置

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

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 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;
    }
公共静态字符串GetHeader(字节[]src)
{
如果(src.Length>0)
使用(PdfReader读取器=新PdfReader(src))
{
使用(MemoryStream ms=new MemoryStream())
{
使用(PdfStamper压模=新PdfStamper(读卡器,ms))
{
字典信息=reader.info;
如果(!info.Keys.Contains(“Title”))
返回null;
其他的
返回信息[“标题”];
}
}
}
其他的
返回null;
}

您能否提供更多详细信息,特别是文件是如何下载到客户端的?您需要在此处提供更多信息。下载文件的是什么,从哪里下载?你的代码放在哪里?你需要有一个原始名称的存储。@Coding Gorilla。。。嗯,我没有任何具体的解决办法,我愿意听取建议。我想给他提供一些链接,可以返回带有原始文件名的文件(位置)。您的文件是如何存储的?您是从数据库中检索它,还是将其存储在文件系统中?请在中检查粘贴的链接answer@ile:那没关系。您可以使用:Response.BinaryWrite(fileContent);远处。在编写任何响应之前,必须调用Response.AppendHeader,否则它将无法工作。您还应该首先设置mime类型:Response.ContentType=“text/html”;好的,谢谢,我试试看。顺便说一句,文件是存储在DB中还是存储在文件系统中并不重要?(我的案例是文件系统)请添加一些注释,说明代码的作用;请用英语。顺致敬意,
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;
    }