mongodb gridfs中的DownloadAsBytes创建空文件

时间:2018-07-06 10:28:27

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

我正在将文件上传到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;

UI代码

$.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);
             }
         }
     }

  });

下载后的文件为空。 如果你们指出我正确的方向,我真的会很开心。

1 个答案:

答案 0 :(得分:0)

我如下更改了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;

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