Saving File Using Bucket, i am able to save file and content type to database, But Not Able to download file with their extension(content)

186 views
Skip to first unread message

OmIndia Tech India

unread,
Oct 27, 2017, 2:32:10 AM10/27/17
to mongodb-user

Help me how to get content type column value at download time ?



C#

public void DownloadFileFromMongoDb(string DatabaseName, string Coll_or_ChunkNam, ObjectId FileID)
    {
        IMongoDatabase database = ConnectMongoDatabase(DatabaseName);
        var BUcket_Option = new GridFSBucketOptions
        {
            BucketName = Coll_or_ChunkNam,
            WriteConcern = WriteConcern.WMajority,
            ReadPreference = ReadPreference.Secondary
            //  ChunkSizeBytes = 1048576, // 1MB
        };
        IGridFSBucket bucket = new GridFSBucket(database, BUcket_Option);
       
 if (FileID != null)
        {
            byte[] buffer = ReadFully(bucket.OpenDownloadStream(FileID));
            string mimeType = string.Empty;
            System.Web.HttpContext.Current.Response.Buffer = true;
            System.Web.HttpContext.Current.Response.Clear();
            System.Web.HttpContext.Current.Response.ContentType = mimeType;
            System.Web.HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=" + FileID + ".pdf");
            System.Web.HttpContext.Current.Response.BinaryWrite(buffer); // create the file
            System.Web.HttpContext.Current.Response.Flush();
        }
    }
ddddd.png

Kevin Adistambha

unread,
Nov 2, 2017, 9:00:45 PM11/2/17
to mongodb-user

Hi

System.Web.HttpContext.Current.Response.ContentType = mimeType;

If I understand correctly, you need to set the mimeType variable to the proper content type. However the contentType field in the database is not a proper MIME type. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types for a description of valid MIME types.

You didn’t specify how you query the relevant file, but in the mongo shell the code should look similar to:

var file = db.Txt.files.findOne({_id: <the file _id>})
var contentType = file.contentType

If executed in the mongo shell, the contentType variable should contain e.g. .txt as stored in the database.

System.Web.HttpContext.Current.Response.AddHeader(“content-disposition”, “attachment; filename=” + FileID + “.pdf”);

Having said that, I’m not sure I understand why the pdf extension is hardcoded in the next line. Is this intentional?

For more information, please see:

Best regards
Kevin

Reply all
Reply to author
Forward
0 new messages