question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

FileStorage.Upload from stream does not seem to be working

See original GitHub issue

Hey David,

I have an issue with uploading images to LiteDB using the FileStorage.Upload method. Below is the code snipped that is failing:

using( var image = Image.FromFile("C:\\Temp\\testfile.jpg").GetThumbnailImage(200, 200, null, IntPtr.Zero))
using (var stream = new MemoryStream())
{
    image.Save(stream, ImageFormat.Jpeg);
    Database.FileStorage.Upload(Guid.NewGuid().ToString(), "testfile.jpg", stream);
}

When I debug I see that the stream contains data, but it does not seem to get written to the database. I see the document in the database with the filename, Id, etc. But the chunk-size remains 0.

Using OpenWrite and saving the image to the LiteFileStream directly does work, however, here I get an error when trying to read from the collection while OpenWrite is still writing to the database:

An exception of type ‘System.IO.IOException’ occurred in LiteDB.dll but was not handled in user code

Additional information: The requested operation cannot be performed on a file with a user-mapped section open.

Stack trace:

   at System.IO.FileStream.SetLengthCore(Int64 value)
   at System.IO.FileStream.SetLength(Int64 value)
   at LiteDB.FileDiskService.SetLength(Int64 fileSize) in FileDiskService.cs:line 129
   at LiteDB.FileDiskService.ClearJournal(UInt32 lastPageID) in FileDiskService.cs:line 191
   at LiteDB.TransactionService.PersistDirtyPages() in TransactionService.cs:line 79
   at LiteDB.LiteEngine.Transaction[T](String collection, Boolean addIfNotExists, Func`2 action) in LiteEngine.cs:line 1192
   at LiteDB.LiteEngine.Insert(String collection, IEnumerable`1 docs, BsonType autoId) in LiteEngine.cs:line 886
   at LiteDB.LiteEngine.Insert(String collection, BsonDocument doc, BsonType autoId) in LiteEngine.cs:line 873
   at LiteDB.LiteStorage.OpenWrite(String id, String filename, BsonDocument metadata) in LiteStorage.cs:line 37

Ok, so actually I have 2 problems it seems. So either I am doing something very wrong or there really is a problem with the Upload method. Any ideas?

Sincerely, Glenn

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Comments:9 (3 by maintainers)

github_iconTop GitHub Comments

3reactions
rollschcommented, May 17, 2019

This is not intuitive, I spent 3 hours debugging the same issue. I’ve never had to manually set my stream.Position = 0 in any other libraries.

Maybe you could check if stream.Position == stream.Length or if the number of bytes copies is 0 and throw a useful exception to the user?

I’ve made a small set of extension methods to handle a few un-intuitive things like this.

` public static class LiteDatabaseExtensions {

    public static LiteFileInfo UploadSafe(this LiteStorage db, string id, string filename, Stream stream)
    {
        stream.Position = 0;
        return db.Upload(MakeSafe(id), MakeSafe(filename), stream);
    }

    public static bool DeleteSafe(this LiteStorage db, string id)
    {
        return db.Delete(MakeSafe(id));
    }

    public static LiteFileStream OpenReadSafe(this LiteStorage db, string id)
    {

        return db.OpenRead(MakeSafe(id));
    }

    public static bool ExistsSafe(this LiteStorage db, string id)
    {
        return db.Exists(MakeSafe(id));
    }


    private static string MakeSafe(string id)
    {
        id = id.Replace(@"\", "_");
        id = id.Replace(":", "-");
        return id;
    }
}`
0reactions
mbdavidcommented, Aug 22, 2018

You always need be sure that you stream are at beginning position. LiteDB will read you stream from current position to end. If your stream already at end, there is nothing to read.

In you case, the problem is image.Save that read first stream (your image) to create a thumbnail. This method Save run over your memory stream (to save the bytes) and do not get back to first position (to be saved on litedb).

Its not about how LiteDB upload but most about how Stream works. If you write direct your image (with no thumbnail) where is not need set position = 0 because already in begin.

using (var stream = new FileStream("yourphoto.png"))
{
    // stream position are in position 0 because do not start reading yet
    Database.FileStorage.Upload(Guid.NewGuid().ToString(), "testfile.jpg", stream);
    // now, if you check position here, you will see Position = Length
}
Read more comments on GitHub >

github_iconTop Results From Across the Web

c# - LiteDB db.FileStorage.Upload stream method never ...
After bashing my head for a while i realized the stream was actually failing to read due to the initial position of the...
Read more >
Is anyone having issues to upload a video to Stream?
A recorded meeting in Teams failed to upload to Streams and the upload button is missing from Streams. I can't find any way...
Read more >
Handling File Uploads With Flask - miguelgrinberg.com
The FileStorage object gives us a stream, so the most convenient option is to read a safe amount of data from it and...
Read more >
GridFS Guide: How to Upload Files and Images ...
We initialize a GridFS stream as seen in the code below. The stream is needed to read the files from the database and...
Read more >
Upload objects from a filesystem | Cloud Storage
Click the Upload Files button, select the files you want to upload in the dialog that appears, and click Open. Note: If you...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found