Login or Sign Up to become a member!
LessThanDot Sit Logo

LessThanDot

Web Developer

Less Than Dot is a community of passionate IT professionals and enthusiasts dedicated to sharing technical knowledge, experience, and assistance. Inside you will find reference materials, interesting technical discussions, and expert tips and commentary. Once you register for an account you will have immediate access to the forums and all past articles and commentaries.

LTD Social Sitings

Lessthandot twitter Lessthandot Linkedin Lessthandot friendfeed Lessthandot facebook Lessthandot rss

Note: Watch for social icons on posts by your favorite authors to follow their postings on these and other social sites.

Your profile

    Search

    XML Feeds

    Google Ads

    « Nancy and returning a pdfSupport for segments in easyhttp »
    comments

    Introduction

    I have been using Nancy for a few weeks now and made a demo application that you can find on Github.

    Today I will add the ability for you to add a picture to a user.

    The upload

    For this we need to change our UsersModule and add a few methods.

    First we add a get so that we can show a page with the userdata and an upload form. Something like this.

    1. Get["/users/userimageupload/{Id}"] = parameters =>
    2.             {
    3.                 Guid result;
    4.                 var isGuid = Guid.TryParse(parameters.id, out result);
    5.                 var user = userService.GetById(result);
    6.                 if (isGuid && user != null)
    7.                 {
    8.                     return View["UploadUserImage",user];
    9.                 }
    10.                 return HttpStatusCode.NotFound;
    11.             };

    Nothing special there, we just ask for the Id, check if it is there and if it is we show the view.
    This will use the following view.

    1. @inherits Nancy.ViewEngines.Razor.NancyRazorViewBase<NancyDemo.Csharp.Model.UserModel>
    2. @{
    3.     ViewBag.Title = "Add user image page";
    4.     Layout = "Master.cshtml";
    5. }
    6.  
    7.  
    8. @section menu
    9. {
    10. Rendersection("menu")
    11. }
    12. @section menuitems
    13. {
    14.     <a href="/users">Users</a>
    15. }
    16.  
    17. <h1>Welcome to the add user image page</h1>
    18. <table>
    19.     <tr>
    20.         <td>Id</td>
    21.         <td>@Model.Id</td>
    22.     </tr>
    23.     <tr>
    24.         <td>Name</td>
    25.         <td>@Model.Name</td>
    26.     </tr>
    27.     <tr>
    28.         <td>RealName</td>
    29.         <td>@Model.RealName</td>
    30.     </tr>
    31.     <tr>
    32.         <td>Password</td>
    33.         <td>@Model.Password</td>
    34.     </tr>
    35. </table>
    36. <form action="/users/userimageupload/@Model.Id" method="post" enctype="multipart/form-data">
    37.     <input name="upload" type="file" size="40" />
    38.     <input type="submit" value="Post!" />
    39. </form>

    This will look something like this.

    All the userdata is shown and the form to upload the file.

    Now we need a Post method in our module to intercept when the user clicks on post.

    1. Post["/users/userimageupload/{Id}"] = parameters =>
    2.                 {
    3.                     Guid result;
    4.                     var isGuid = Guid.TryParse(parameters.Id, out result);
    5.                     var user = userService.GetById(result);
    6.                
    7.                     var file = this.Request.Files.FirstOrDefault();
    8.  
    9.                     if (isGuid && user != null && file != null)
    10.                     {
    11.                         var fileDetails = string.Format("{3} - {0} ({1}) {2}bytes", file.Name, file.ContentType, file.Value.Length, file.Key);
    12.                         user.FileDetails = fileDetails;
    13.                         var filename = Path.Combine(pathProvider.GetRootPath(), "Images", user.Id + ".jpeg");
    14.  
    15.                         using (var fileStream = new FileStream(filename, FileMode.Create))
    16.                         {
    17.                             file.Value.CopyTo(fileStream);
    18.                         }
    19.                         return View[user];
    20.                     }
    21.                     return HttpStatusCode.NotFound;
    22.                 };

    This accepts an Id as parameter. and saves the first file in the stream to a folder in our project called Images and saves the filedetails in the user object. You can also see that we use the pathprovider. We can inject this pathprovider in our module via the constructor like this.

    public UsersModule(UserService userService, IRootPathProvider pathProvider)

    And as you can see we return to our userpage.

    The user

    The userpage needs to show the image.

    We do this by adding a Get to our usermodule.

    1. Get["/users/getimage/{Id}"] = parameters =>
    2.                 {
    3.                     Guid result;
    4.                     var isGuid = Guid.TryParse(parameters.Id, out result);
    5.                     var filename = Path.Combine(pathProvider.GetRootPath(), "Images", result.ToString() + ".jpeg");
    6.                     if (!File.Exists(filename)) filename = Path.Combine(pathProvider.GetRootPath(), "Images", "emptyuser.jpeg");
    7.                     var stream = new FileStream(filename, FileMode.Open);
    8.                     return Response.FromStream(stream, "image/jpeg");
    9.                 };

    This looks to see if an image exists and if not than it shows a default image.

    With picture.

    With default picture.

    This means our view is changed a little bit.

    1. @inherits Nancy.ViewEngines.Razor.NancyRazorViewBase<NancyDemo.Csharp.Model.UserModel>
    2.  
    3. @{
    4.     ViewBag.Title = "User page";
    5.     Layout = "Master.cshtml";
    6. }
    7.  
    8. @section menu
    9. {
    10.     RenderSection("menu")
    11. }
    12. @section menuitems
    13. {
    14.     <a href="/users">Users</a>
    15. }
    16.  
    17.     <h1>Welcome to the user page</h1>
    18. <table>
    19.     <tr>
    20.         <td>Id</td>
    21.         <td>@Model.Id</td>
    22.     </tr>
    23.     <tr>
    24.         <td>Name</td>
    25.         <td>@Model.Name</td>
    26.     </tr>
    27.     <tr>
    28.         <td>RealName</td>
    29.         <td>@Model.RealName</td>
    30.     </tr>
    31.     <tr>
    32.         <td>Password</td>
    33.         <td>@Model.Password</td>
    34.     </tr>
    35.     <tr>
    36.         <td>FileDetails</td>
    37.         <td>@Model.FileDetails</td>
    38.     </tr>
    39. </table>
    40. <a href="/users/userimageupload/@Model.Id">Upload image</a><br />
    41. <img src="/users/getimage/@Model.Id"/>

    And that's it

    Conclusion

    It's not all that hard to do, once you know how.

    Special thanks to jchannon, Grumpydev and TheCodeJunkie for the help.

    About the Author

    User bio imageChris is awesome.
    Social SitingsTwitterHomePageLTD RSS Feed
    InstapaperVote on HN

    2 comments

    Comment from: Jonathan Channon [Visitor] Email · http://blog.jonathanchannon.com
    Jonathan Channon Nice work! :)
    12/28/12 @ 06:41
    Comment from: Eli Weinstock-Herman (tarwn) [Member]
    Eli Weinstock-Herman (tarwn) I'm not sure why, but while I was reading this I had a flashback to what this code would have looked like 10 years ago w/ classic ASP and it reminded me just how far we (web, .Net, LTD-ers) had come.

    And the post content was neat also :)
    12/28/12 @ 14:22

    Comments are closed for this post.