【问题标题】:DownloadAsBytes in mongodb gridfs creating empty filemongodb gridfs中的DownloadAsBytes创建空文件
【发布时间】:2018-07-06 10:28:27
【问题描述】:

我正在将文件上传到 webapi,它将文件(pdf 和 word 文档)保存到 mongodb gridfs(v 2.6.1)

webapi 代码

 var file = Request.Files[0];
 var fileName = file.FileName;
 var fileType = file.ContentType;
 var document = blabl.UploadFile(fileName, fileType,ReadFully(file.InputStream));

将传入流转换为字节

public static byte[] ReadFully(Stream input)
{
   using (MemoryStream ms = new MemoryStream())
   {
       input.CopyTo(ms);
       return ms.ToArray();
   }
}

GridFs 代码

var bucket = new GridFSBucket(_database, new GridFSBucketOptions
{
    BucketName = bucketName,
    WriteConcern = WriteConcern.WMajority,
    ChunkSizeBytes = 1048576
});

var id = bucket.UploadFromBytes(fileName, source, options);
return id;

要下载的代码

var bucket = new GridFSBucket(_database, new GridFSBucketOptions
{
    BucketName = bucketName
});

return bucket.DownloadAsBytes(id);

WebApi

HttpResponseMessage result = Request.CreateResponse(HttpStatusCode.OK);
result.Content = new ByteArrayContent(data);
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
    FileName = "MyPdf.pdf"
};
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
return result;

界面代码

$.ajax({
    url:'path',
    type: 'GET',
    responseType: 'arraybuffer',
     success: function (data)
     {
      var link = document.createElement('a');
       if ('download' in link) 
        {

            try {
             var blob = new Blob([data], { type: contentType });
             var url = urlCreator.createObjectURL(blob);
              link.setAttribute('href', url);
              link.setAttribute("download", filename);
              var event = document.createEvent('MouseEvents');
              event.initMouseEvent('click', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
              link.dispatchEvent(event);

             } catch (ex) 
             {
               console.log(ex);
             }
         }
     }

  });

下载后文件为空。 如果你们指出我正确的方向,我会非常高兴。

【问题讨论】:

    标签: c# mongodb asp.net-web-api gridfs


    【解决方案1】:

    我已将 webapi 代码更改如下

    HttpResponseMessage httpResponseMessage = new HttpResponseMessage();
    httpResponseMessage.Content = new ByteArrayContent(data.ToArray());
    httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
    httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
    httpResponseMessage.Content.Headers.ContentDisposition.FileName = fileName;
    httpResponseMessage.StatusCode = HttpStatusCode.OK;
    return httpResponseMessage;
    

    另外,我忘记了我有一个正在更改响应的委托处理程序。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-12
      • 2015-07-18
      • 1970-01-01
      • 2014-04-28
      • 1970-01-01
      • 2017-10-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多