Muszę wystawić na świat pliki przechowywane w MongoDB GridFs. Pobierając plik otrzymuję stream, który po bezpośrednim wstawieniu w Content pobierany jest jako plik o rozmiarze 0B. Obszedłem problem zapisując plik, a następnie wstawiając go w Content jako FileStream.
Tak wygląda to aktualnie: (Działa)
public HttpResponseMessage Get(string fileId)
{
string root = System.Web.HttpContext.Current.Server.MapPath("~/App_Data/tempFiles/");
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
var stream = new System.IO.MemoryStream();
IGridFSBucket bucket = new GridFSBucket(repository.Database);
var fileBytes = bucket.DownloadAsBytes(new ObjectId(fileId));
using (Stream file = System.IO.File.Create(root+"file.pdf", (int)fileBytes.Length))
{
byte[] bytesInStream = new byte[stream.Length];
stream.Read(fileBytes, 0, fileBytes.Length);
file.Write(fileBytes, 0, fileBytes.Length);
}
response.Content = new StreamContent(new FileStream(root+"file.pdf", FileMode.Open,FileAccess.Read));
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
response.Content.Headers.ContentLength = fileBytes.Length;
response.Content.Headers.ContentDisposition.FileName = "file.pdf";
response.Content.Headers.ContentDisposition.Size = fileBytes.Length;
return response;
}
Ten sposób zwraca pliki o rozmiarze 0B:
public HttpResponseMessage Get(string fileId)
{
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
var stream = new System.IO.MemoryStream();
IGridFSBucket bucket = new GridFSBucket(repository.Database);
bucket.DownloadToStream(new ObjectId(fileId), stream);
response.Content = new StreamContent(stream);
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
response.Content.Headers.ContentLength = stream.Length;
response.Content.Headers.ContentDisposition.FileName = "file.pdf";
response.Content.Headers.ContentDisposition.Size = stream.Length;
return response;
}
Ma ktoś pomysł jak poprawić wersję drugą, aby nie musieć zapisywać plików pobranych z bazy?