ZVenue
ZVenue

Reputation: 5027

Open attachment for user in the UI in ASP.NET MVC

What I am trying to do - When user clicks on a link, get the attachment from RavenDB and open it automatically for the user.

On Click of a link - I pass the attachment id of a attachment (already saved in RavenDB) to the controller method via view/ajax. Once inside the controller method, I want to get the attachment and display/open the attachment for the user.

View :

<a href onclick="GetAttachment('<%= Model.Id %>');"> See attachment </a>

Ajax/JS

function GetAttachment(id) {   

$.ajax({
    type: 'POST',
    url: '/ControllerName/GetMethod',
    data: id,
    contentType: 'application/json; charset=utf-8',
    success: function (msg) {
        if (msg.Success) {               
        }
        else {               
        }
     }       
  });
}

Controller :

    public string GetMethod(string id)
    {          
        var dbCommands = session.Advanced.DatabaseCommands;
        var attachment = dbCommands.GetAttachment(id);
       //Here - How do I use above lines of code to get hold of the 
       // attachment and open it for the user.
    }

Thank you for the help.

Upvotes: 1

Views: 1316

Answers (2)

eulerfx
eulerfx

Reputation: 37719

The RavenDB Attachment class has a Data property of type Func<Stream> which is a thunk to the byte stream for the attachment. The stream is what you need to return in your MVC controller:

public FileResult GetMethod(string id)
{          
    var dbCommands = session.Advanced.DatabaseCommands;
    var attachment = dbCommands.GetAttachment(id);
    return File(attachment.Data(), "fileName");
}

Upvotes: 3

Kirill Bestemyanov
Kirill Bestemyanov

Reputation: 11964

Something like this: Controller:

public FileResult GetMethod(string id)
{          
    var name = "filename.extension";
    var dbCommands = session.Advanced.DatabaseCommands;
    var attachment = dbCommands.GetAttachment(id);
    var stream = new MemoryStream(attachment.Data);
    return new FileStreamResult(stream, name);
}

View:

@Html.ActionLink("See attachment", "GetMethod", "ControllerName", new {id = ModelId}, null)

You need get MemoryStream of file from database or transfer your file into MemoryStream

Upvotes: 1

Related Questions