Why are .docx files being corrupted when downloading from an ASP.NET page?

前端 未结 8 948
长发绾君心
长发绾君心 2020-12-03 05:09

I have this following code for bringing page attachments to the user:

private void GetFile(string package, string filename)
{
    var stream = new MemoryStre         


        
8条回答
  •  借酒劲吻你
    2020-12-03 05:22

    I had the same problem while i try to open .docx and .xlsx documents. I solve the problem by defining the cacheability to ServerAndPrivate instead of NoCache

    there is my method to call document:

    public void ProcessRequest(HttpContext context)
    
     {
    
    
           var fi = new FileInfo(context.Request.Path);
            var mediaId = ResolveMediaIdFromName(fi.Name);
            if (mediaId == null) return;
    
            int mediaContentId;
            if (!int.TryParse(mediaId, out mediaContentId)) return;
    
            var media = _repository.GetPublicationMediaById(mediaContentId);
            if (media == null) return;
    
            var fileNameFull = string.Format("{0}{1}", media.Name, media.Extension);
            context.Response.Clear();
            context.Response.AddHeader("content-disposition", string.Format("attachment;filename={0}", fileNameFull));            
            context.Response.Charset = "";
            context.Response.Cache.SetCacheability(HttpCacheability.ServerAndPrivate);
            context.Response.ContentType = media.ContentType;
            context.Response.BinaryWrite(media.Content);
            context.Response.Flush();          
            context.Response.End();          
        }
    

提交回复
热议问题