Image Upload in Mvc 4 Razor Example
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Working with Images in an ASP.NET Spider web Pages (Razor) Site
by Tom FitzMacken
This article shows yous how to add, display, and manipulate images (resize, flip, and add watermarks) in an ASP.NET Web Pages (Razor) website.
What you'll learn:
- How to add an image to a page dynamically.
- How to let users upload an paradigm.
- How to resize an image.
- How to flip or rotate an image.
- How to add a watermark to an image.
- How to use an paradigm as a watermark.
These are the ASP.Cyberspace programming features introduced in the commodity:
- The
WebImage
helper.- The
Path
object, which provides methods that let you manipulate path and file names.Software versions used in the tutorial
- ASP.Net Spider web Pages (Razor) 2
- WebMatrix ii
This tutorial also works with WebMatrix 3.
Adding an Image to a Web Page Dynamically
You can add images to your website and to individual pages while y'all're developing the website. You can too let users upload images, which might be useful for tasks like letting them add a profile photo.
If an image is already available on your site and you just desire to display information technology on a folio, you use an HTML <img>
element similar this:
<img src="images/Photo1.jpg" alt="Sample Photograph" />
Sometimes, though, you demand to be able to display images dynamically — that is, you don't know what image to brandish until the page is running.
The procedure in this section shows how to display an paradigm on the wing where users specify the paradigm file name from a list of image names. They select the name of the paradigm from a drop-downward list, and when they submit the folio, the image they selected is displayed.
-
In WebMatrix, create a new website.
-
Add a new folio named DynamicImage.cshtml.
-
In the root binder of the website, add a new folder and name it images.
-
Add four images to the images folder yous just created. (Any images you take handy will practise, but they should fit onto a page.) Rename the images Photo1.jpg, Photo2.jpg, Photo3.jpg, and Photo4.jpg. (You lot won't utilise Photo4.jpg in this procedure, but yous'll employ information technology afterward in the commodity.)
-
Verify that the four images are not marked as read-simply.
-
Supersede the existing content in the folio with the post-obit:
@{ var imagePath= ""; if( Request["photoChoice"] != null){ imagePath = @"images\" + Request["photoChoice"]; } } <!DOCTYPE html> <html> <head> <championship>Display Epitome on the Fly</title> </caput> <trunk> <h1>Displaying an Image On the Fly</h1> <grade method="post" action=""> <div> I want to see: <select proper name="photoChoice"> <option value="Photo1.jpg">Photo 1</option> <selection value="Photo2.jpg">Photo 2</choice> <option value="Photo3.jpg">Photo 3</option> </select> <input blazon="submit" value="Submit" /> </div> <div style="padding:10px;"> @if(imagePath != ""){ <img src="@imagePath" alt="Sample Image" width="300px" /> } </div> </grade> </body> </html>
The trunk of the page has a drop-down listing (a
<select>
chemical element) that'southward namedphotoChoice
. The list has iii options, and thevalue
attribute of each list option has the name of 1 of the images that you put in the images folder. Essentially, the list lets the user select a friendly name similar "Photograph 1", and it and so passes the .jpg file name when the page is submitted.In the code, y'all can become the user's selection (in other words, the image file proper name) from the list by reading
Request["photoChoice"]
. You outset run across if at that place'south a selection at all. If there is, you lot construct a path for the prototype that consists of the proper name of the folder for the images and the user'southward paradigm file name. (If you tried to construct a path but in that location was nothing inRequest["photoChoice"]
, yous'd become an fault.) This results in a relative path like this:images/Photo1.jpg
The path is stored in variable named
imagePath
that you'll need later in the page.In the trunk, at that place's also an
<img>
element that's used to display the prototype that the user picked. Thesrc
attribute isn't fix to a file name or URL, like y'all'd do to display a static element. Instead, it'southward ready to@imagePath
, meaning that information technology gets its value from the path you set in code.The first time that the page runs, though, there's no image to display, considering the user hasn't selected anything. This would unremarkably mean that the
src
aspect would be empty and the prototype would show upwardly as a red "x" (or whatever the browser renders when it tin't observe an image). To preclude this, you put the<img>
element in anif
block that tests to meet whether theimagePath
variable has annihilation in it. If the user made a pick,imagePath
contains the path. If the user didn't pick an image or if this is the starting time time the folio is displayed, the<img>
chemical element isn't even rendered. -
Salvage the file and run the page in a browser. (Make certain the page is selected in the Files workspace earlier you lot run information technology.)
-
Select an image from the drib-down list and so click Sample Image. Brand sure that you meet unlike images for different choices.
Uploading an Epitome
The previous instance showed you lot how to display an image dynamically, but it worked only with images that were already on your website. This procedure shows how to let users upload an image, which is then displayed on the page. In ASP.NET, y'all can manipulate images on the fly using the WebImage
helper, which has methods that let you create, dispense, and salve images. The WebImage
helper supports all the common web paradigm file types, including .jpg, .png, and .bmp. Throughout this article, you lot'll apply .jpg images, but you can use any of the image types.
-
Add a new page and proper name it UploadImage.cshtml.
-
Replace the existing content in the page with the following:
@{ WebImage photo = null; var newFileName = ""; var imagePath = ""; if(IsPost){ photo = WebImage.GetImageFromRequest(); if(photo != null){ newFileName = Guid.NewGuid().ToString() + "_" + Path.GetFileName(photo.FileName); imagePath = @"images\" + newFileName; photo.Save(@"~\" + imagePath); } } } <!DOCTYPE html> <html> <head> <title>Image Upload</championship> </head> <body> <form activeness="" method="post" enctype="multipart/class-information"> <fieldset> <fable> Upload Image </legend> <label for="Epitome">Paradigm</characterization> <input type="file" name="Image" /> <br/> <input type="submit" value="Upload" /> </fieldset> </form> <h1>Uploaded Prototype</h1> @if(imagePath != ""){ <div form="result"> <img src="@imagePath" alt="image" /> </div> } </body> </html>
The body of the text has an
<input blazon="file">
chemical element, which lets users select a file to upload. When they click Submit, the file they picked is submitted along with the form.To get the uploaded epitome, you employ the
WebImage
helper, which has all sorts of useful methods for working with images. Specifically, you useWebImage.GetImageFromRequest
to get the uploaded epitome (if any) and store it in a variable namedphotograph
.A lot of the work in this instance involves getting and setting file and path names. The result is that you want to go the proper name (and but the proper name) of the image that the user uploaded, and and so create a new path for where you're going to store the prototype. Because users could potentially upload multiple images that have the same name, you use a bit of extra code to create unique names and brand sure that users don't overwrite existing pictures.
If an epitome actually has been uploaded (the test
if (photo != nothing)
), you go the image name from the image'due southFileName
property. When the user uploads the epitome,FileName
contains the user's original name, which includes the path from the user'due south reckoner. It might expect like this:C:\Users\Joe\Pictures\SamplePhoto1.jpg
Y'all don't want all that path information, though — yous just want the actual file name (SamplePhoto1.jpg). You can strip out just the file from a path by using the
Path.GetFileName
method, like this:Path.GetFileName(photo.FileName)
You lot then create a new unique file name by adding a GUID to the original proper name. (For more than well-nigh GUIDs, run across About GUIDs afterward in this commodity.) So y'all construct a consummate path that you tin can use to relieve the prototype. The salvage path is made up of the new file name, the binder (images), and the current website location.
Annotation
In order for your code to relieve files in the images binder, the application needs read-write permissions for that folder. On your development estimator this is not typically an outcome. Nonetheless, when you lot publish your site to a hosting provider's web server, you might demand to explicitly prepare those permissions. If you run this code on a hosting provider's server and get errors, cheque with the hosting provider to notice out how to set those permissions.
Finally, y'all laissez passer the save path to the
Salve
method of theWebImage
helper. This stores the uploaded prototype under its new name. The save method looks similar this:photo.Save(@"~\" + imagePath)
. The complete path is appended to@"~\"
, which is the electric current website location. (For data about the~
operator, see Introduction to ASP.Internet Web Programming Using the Razor Syntax.)As in the previous instance, the body of the page contains an
<img>
element to display the image. IfimagePath
has been set, the<img>
chemical element is rendered and itssrc
attribute is prepare to theimagePath
value. -
Run the page in a browser.
-
Upload an image and make sure information technology's displayed in the page.
-
In your site, open the images folder. You see that a new file has been added whose file name looks something like this::
45ea4527-7ddd-4965-b9ca-c6444982b342_MyPhoto.png
This is the image that you lot uploaded with a GUID prefixed to the proper name. (Your own file will accept a dissimilar GUID and probably is named something different than MyPhoto.png.)
Tip
About GUIDs
A GUID (globally-unique ID) is an identifier that's usually rendered in a format similar this: 936DA01F-9ABD-4d9d-80C7-02AF85C822A8
. The numbers and letters (from A-F) differ for each GUID, merely they all follow the pattern of using groups of 8-four-4-iv-12 characters. (Technically, a GUID is a sixteen-byte/128-scrap number.) When you need a GUID, you tin call specialized code that generates a GUID for you. The idea backside GUIDs is that between the enormous size of the number (3.iv x 1038) and the algorithm for generating information technology, the resulting number is nearly guaranteed to be one of a kind. GUIDs therefore are a adept way to generate names for things when you must guarantee that you won't use the same name twice. The downside, of form, is that GUIDs aren't particularly user friendly, and so they tend to be used when the name is used only in lawmaking.
Resizing an Image
If your website accepts images from a user, you lot might desire to resize the images before you brandish or save them. You tin once again use the WebImage
helper for this.
This procedure shows how to resize an uploaded prototype to create a thumbnail and then salvage the thumbnail and original image in the website. Y'all display the thumbnail on the folio and use a hyperlink to redirect users to the full-sized paradigm.
-
Add a new page named Thumbnail.cshtml.
-
In the images folder, create a subfolder named thumbs.
-
Supersede the existing content in the page with the following:
@{ WebImage photograph = null; var newFileName = ""; var imagePath = ""; var imageThumbPath = ""; if(IsPost){ photo = WebImage.GetImageFromRequest(); if(photograph != nix){ newFileName = Guid.NewGuid().ToString() + "_" + Path.GetFileName(photograph.FileName); imagePath = @"images\" + newFileName; photo.Relieve(@"~\" + imagePath); imageThumbPath = @"images\thumbs\" + newFileName; photo.Resize(width: sixty, height: sixty, preserveAspectRatio: truthful, preventEnlarge: true); photo.Save(@"~\" + imageThumbPath); } } } <!DOCTYPE html> <html> <head> <title>Resizing Prototype</title> </head> <trunk> <h1>Thumbnail Epitome</h1> <course action="" method="post" enctype="multipart/form-information"> <fieldset> <fable> Creating Thumbnail Image </fable> <label for="Epitome">Image</characterization> <input type="file" name="Paradigm" /> <br/> <input blazon="submit" value="Submit" /> </fieldset> </grade> @if(imagePath != ""){ <div form="result"> <img src="@imageThumbPath" alt="Thumbnail image" /> <a href="@Html.AttributeEncode(imagePath)" target="_Self"> View full size </a> </div> } </body> </html>
This code is similar to the lawmaking from the previous instance. The difference is that this code saves the image twice, one time normally and once after y'all create a thumbnail re-create of the epitome. Starting time y'all get the uploaded paradigm and salvage it in the images folder. Yous then construct a new path for the thumbnail image. To actually create the thumbnail, you lot call the
WebImage
helper'sResize
method to create a 60-pixel by 60-pixel image. The example shows how you preserve the aspect ratio and how you can preclude the prototype from being enlarged (in example the new size would actually make the image larger). The resized prototype is and so saved in the thumbs subfolder.At the end of the markup, you use the same
<img>
element with the dynamicsrc
attribute that yous've seen in the previous examples to conditionally show the epitome. In this instance, you display the thumbnail. You as well apply an<a>
element to create a hyperlink to the big version of the image. As with thesrc
attribute of the<img>
element, you set thehref
attribute of the<a>
element dynamically to any is inimagePath
. To make sure that the path tin work as a URL, you lot laissez passerimagePath
to theHtml.AttributeEncode
method, which converts reserved characters in the path to characters that are ok in a URL. -
Run the folio in a browser.
-
Upload a photo and verify that the thumbnail is shown.
-
Click the thumbnail to encounter the full-size paradigm.
-
In the images and images/thumbs, note that new files have been added.
Rotating and Flipping an Image
The WebImage
helper also lets you flip and rotate images. This procedure shows how to go an image from the server, flip the image upside down (vertically), save it, so display the flipped image on the folio. In this case, you're just using a file you already have on the server (Photo2.jpg). In a real awarding, you'd probably flip an epitome whose name you get dynamically, like yous did in previous examples.
-
Add together a new folio named FlipImage.cshtml.
-
Supercede the existing content in the folio with the post-obit:
@{ var imagePath= ""; WebImage photo = new WebImage(@"~\Images\Photo2.jpg"); if(photo != null){ imagePath = @"images\Photo2.jpg"; photo.FlipVertical(); photo.Save(@"~\" + imagePath); } } <!DOCTYPE html> <html> <caput> <championship>Get Image From File</title> <meta http-equiv="content-blazon" content="text/html;charset=utf-8" /> </head> <body> <h1>Flip Image Vertically</h1> @if(imagePath != ""){ <div course="result"> <img src="@imagePath" alt="Paradigm" /> </div> } </trunk> </html>
The lawmaking uses the
WebImage
helper to get an prototype from the server. You create the path to the image using the same technique y'all used in earlier examples for saving images, and yous pass that path when you create an image usingWebImage
:WebImage photo = new WebImage(@"~\Images\Photo2.jpg");
If an image is establish, you construct a new path and file name, like you did in earlier examples. To flip the epitome, yous call the
FlipVertical
method, and and so you relieve the epitome again.The paradigm is again displayed on the page by using the
<img>
element with thesrc
attribute set toimagePath
. -
Run the folio in a browser. The image for Photo2.jpg is shown upside downwardly.
-
Refresh the page or asking the page over again to see the image is flipped right side up over again.
To rotate an image, you utilize the same code, except that instead of calling the FlipVertical
or FlipHorizontal
, you call RotateLeft
or RotateRight
.
Calculation a Watermark to an Paradigm
When yous add images to your website, y'all might want to add a watermark to the prototype before you save information technology or display it on a page. People often utilise watermarks to add copyright data to an image or to annunciate their business organization proper name.
-
Add together a new page named Watermark.cshtml.
-
Replace the existing content in the page with the following:
@{ var imagePath= ""; WebImage photo = new WebImage(@"~\Images\Photo3.jpg"); if(photo != null){ imagePath = @"images\Photo3.jpg"; photo.AddTextWatermark("My Watermark", fontColor:"Yellow", fontFamily: "Arial"); photo.Save(@"~\" + imagePath); } } <!DOCTYPE html> <html> <head> <title>Water Mark</title> <meta http-equiv="content-type" content="text/html;charset=utf-8" /> </head> <torso> <h1>Adding a Watermark to an Epitome</h1> @if(imagePath != ""){ <div grade="result"> <img src="@imagePath" alt="Prototype" /> </div> } </torso> </html>
This code is like the code in the FlipImage.cshtml page from earlier (although this time it uses the Photo3.jpg file). To add the watermark, yous call the
WebImage
helper'sAddTextWatermark
method earlier y'all save the epitome. In the phone call toAddTextWatermark
, y'all pass the text "My Watermark", set the font color to yellow, and set the font family to Arial. (Although it'south not shown hither, theWebImage
helper also lets yous specify opacity, font family unit and font size, and the position of the watermark text.) When you save the epitome it must not be read-merely.As you've seen earlier, the image is displayed on the page past using the
<img>
element with the src attribute fix to@imagePath
. -
Run the page in a browser. Notice the text "My Watermark" at the bottom-correct corner of the image.
Using an Image As a Watermark
Instead of using text for a watermark, you tin use some other image. People sometimes utilize images similar a company logo as a watermark, or they use a watermark image instead of text for copyright information.
-
Add together a new page named ImageWatermark.cshtml.
-
Add an prototype to the images folder that you tin use as a logo, and rename the image MyCompanyLogo.jpg. This image should be an image that you lot can run across clearly when it's set to 80 pixels wide and 20 pixels high.
-
Replace the existing content in the folio with the following:
@{ var imagePath = ""; WebImage WatermarkPhoto = new WebImage(@"~\" + @"\Images\MyCompanyLogo.jpg"); WebImage photo = new WebImage(@"~\Images\Photo4.jpg"); if(photo != nil){ imagePath = @"images\Photo4.jpg"; photograph.AddImageWatermark(WatermarkPhoto, width: 80, height: 20, horizontalAlign:"Center", verticalAlign:"Bottom", opacity:100, padding:10); photo.Save(@"~\" + imagePath); } } <!DOCTYPE html> <html> <caput> <title>Paradigm Watermark</title> <meta http-equiv="content-type" content="text/html;charset=utf-8" /> </head> <torso> <h1>Using an Image as a Watermark</h1> @if(imagePath != ""){ <div class="result"> <img src="@imagePath" alt="Image" /> </div> } </body> </html>
This is some other variation on the code from before examples. In this case, yous call
AddImageWatermark
to add the watermark prototype to the target prototype (Photo3.jpg) before you relieve the epitome. When you callAddImageWatermark
, y'all set its width to eighty pixels and the meridian to 20 pixels. The MyCompanyLogo.jpg paradigm is horizontally aligned in the center and vertically aligned at the bottom of the target prototype. The opacity is prepare to 100% and the padding is set to ten pixels. If the watermark image is bigger than the target image, nothing will happen. If the watermark prototype is bigger than the target prototype and you set the padding for the paradigm watermark to cypher, the watermark is ignored.Every bit before, you display the image using the
<img>
element and a dynamicsrc
attribute. -
Run the page in a browser. Notice that the watermark prototype appears at the bottom of the master image.
Additional Resources
Working with Files in an ASP.Cyberspace Web Pages Site
Introduction to ASP.Cyberspace Web Pages Programming Using the Razor Syntax
Source: https://docs.microsoft.com/en-us/aspnet/web-pages/overview/ui-layouts-and-themes/9-working-with-images