Skip to content

Commit 7328db0

Browse files
committed
Added image upload
1 parent 4f6c3c9 commit 7328db0

File tree

11 files changed

+282
-22
lines changed

11 files changed

+282
-22
lines changed

BookCollection/BookCollection.csproj

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -213,6 +213,8 @@
213213
<Compile Include="Helpers\BC.cs" />
214214
<Compile Include="Helpers\Converters.cs" />
215215
<Compile Include="Helpers\DownloadFileActionResult.cs" />
216+
<Compile Include="Helpers\ImageResult.cs" />
217+
<Compile Include="Helpers\ImageUpload.cs" />
216218
<Compile Include="Helpers\Validators.cs" />
217219
<Compile Include="Logging\ILogger.cs" />
218220
<Compile Include="Logging\TraceLogger.cs" />
@@ -559,9 +561,12 @@
559561
<Content Include="Views\NewBooks\Details.cshtml" />
560562
<Content Include="Views\NewBooks\Edit.cshtml" />
561563
<Content Include="Views\NewBooks\Index.cshtml" />
564+
<Content Include="Views\Books\UploadCover.cshtml" />
565+
<Content Include="Views\Books\UploadCompleted.cshtml" />
562566
</ItemGroup>
563567
<ItemGroup>
564568
<Folder Include="App_Data\" />
569+
<Folder Include="Images\Uploaded\" />
565570
</ItemGroup>
566571
<ItemGroup>
567572
<Content Include="packages.config" />

BookCollection/Controllers/BooksController.cs

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
using BookCollection.DAL;
1010
using BookCollection.Models;
1111
using PagedList;
12+
using BookCollection.Helpers;
1213

1314
namespace BookCollection.Controllers
1415
{
@@ -288,5 +289,75 @@ protected override void Dispose(bool disposing)
288289
}
289290
base.Dispose(disposing);
290291
}
292+
293+
public ActionResult UploadCover(int? id)
294+
{
295+
if (id == null)
296+
{
297+
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
298+
}
299+
Book book = _db.Query<Book>().FirstOrDefault(b => b.BookID == id);
300+
if (book == null)
301+
{
302+
return HttpNotFound();
303+
}
304+
return View(book);
305+
}
306+
307+
public ActionResult UploadCompleted()
308+
{
309+
return View();
310+
}
311+
312+
[HttpPost]
313+
public ActionResult UploadCover(FormCollection formCollection)
314+
{
315+
int id = Convert.ToInt32(formCollection["ID"]);
316+
if (id == null)
317+
{
318+
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
319+
}
320+
Book book = _db.Query<Book>().FirstOrDefault(b => b.BookID == id);
321+
if (book == null)
322+
{
323+
return HttpNotFound();
324+
}
325+
326+
foreach (string item in Request.Files)
327+
{
328+
HttpPostedFileBase file = Request.Files[item] as HttpPostedFileBase;
329+
if (file.ContentLength == 0)
330+
continue;
331+
if (file.ContentLength > 0)
332+
{
333+
// width + height will force size, care for distortion
334+
//Exmaple: ImageUpload imageUpload = new ImageUpload { Width = 800, Height = 700 };
335+
336+
// height will increase the width proportionally
337+
//Example: ImageUpload imageUpload = new ImageUpload { Height= 600 };
338+
339+
// width will increase the height proportionally
340+
ImageUpload imageUpload = new ImageUpload { Width = 300 };
341+
342+
// rename, resize, and upload
343+
//return object that contains {bool Success,string ErrorMessage,string ImageName}
344+
ImageResult imageResult = imageUpload.RenameUploadFile(file);
345+
if (imageResult.Success)
346+
{
347+
//TODO: write the filename to the db
348+
349+
Console.WriteLine(imageResult.ImageName);
350+
return RedirectToAction("UploadCompleted");
351+
}
352+
else
353+
{
354+
// use imageResult.ErrorMessage to show the error
355+
ViewBag.Error = imageResult.ErrorMessage;
356+
}
357+
}
358+
}
359+
360+
return View();
361+
}
291362
}
292363
}
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Linq;
4+
using System.Web;
5+
6+
namespace BookCollection.Helpers
7+
{
8+
public class ImageResult
9+
{
10+
public bool Success { get; set; }
11+
public string ImageName { get; set; }
12+
public string ErrorMessage { get; set; }
13+
}
14+
}
Lines changed: 144 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,144 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Drawing;
4+
using System.Drawing.Drawing2D;
5+
using System.Drawing.Imaging;
6+
using System.IO;
7+
using System.Linq;
8+
using System.Web;
9+
10+
namespace BookCollection.Helpers
11+
{
12+
public class ImageUpload
13+
{
14+
// set default size here
15+
public int Width { get; set; }
16+
17+
public int Height { get; set; }
18+
19+
// folder for the upload, you can put this in the web.config
20+
private readonly string UploadPath = "~/Images/Uploaded/";
21+
22+
public ImageResult RenameUploadFile(HttpPostedFileBase file, Int32 counter = 0)
23+
{
24+
var fileName = Path.GetFileName(file.FileName);
25+
26+
string prepend = "item_";
27+
string finalFileName = prepend + ((counter).ToString()) + "_" + fileName;
28+
if (System.IO.File.Exists
29+
(HttpContext.Current.Request.MapPath(UploadPath + finalFileName)))
30+
{
31+
//file exists => add country try again
32+
return RenameUploadFile(file, ++counter);
33+
}
34+
//file doesn't exist, upload item but validate first
35+
return UploadFile(file, finalFileName);
36+
}
37+
38+
private ImageResult UploadFile(HttpPostedFileBase file, string fileName)
39+
{
40+
ImageResult imageResult = new ImageResult { Success = true, ErrorMessage = null };
41+
42+
var path = Path.Combine(HttpContext.Current.Request.MapPath(UploadPath), fileName);
43+
string extension = Path.GetExtension(file.FileName);
44+
45+
//make sure the file is valid
46+
if (!ValidateExtension(extension))
47+
{
48+
imageResult.Success = false;
49+
imageResult.ErrorMessage = "Invalid Extension";
50+
return imageResult;
51+
}
52+
53+
try
54+
{
55+
file.SaveAs(path);
56+
57+
Image imgOriginal = Image.FromFile(path);
58+
59+
//pass in whatever value you want
60+
Image imgActual = Scale(imgOriginal);
61+
imgOriginal.Dispose();
62+
imgActual.Save(path);
63+
imgActual.Dispose();
64+
65+
imageResult.ImageName = fileName;
66+
67+
return imageResult;
68+
}
69+
catch (Exception ex)
70+
{
71+
// you might NOT want to show the exception error for the user
72+
// this is generally logging or testing
73+
74+
imageResult.Success = false;
75+
imageResult.ErrorMessage = ex.Message;
76+
return imageResult;
77+
}
78+
}
79+
80+
private bool ValidateExtension(string extension)
81+
{
82+
extension = extension.ToLower();
83+
switch (extension)
84+
{
85+
case ".jpg":
86+
return true;
87+
case ".png":
88+
return true;
89+
case ".gif":
90+
return true;
91+
case ".jpeg":
92+
return true;
93+
default:
94+
return false;
95+
}
96+
}
97+
98+
private Image Scale(Image imgPhoto)
99+
{
100+
float sourceWidth = imgPhoto.Width;
101+
float sourceHeight = imgPhoto.Height;
102+
float destHeight = 0;
103+
float destWidth = 0;
104+
int sourceX = 0;
105+
int sourceY = 0;
106+
int destX = 0;
107+
int destY = 0;
108+
109+
// force resize, might distort image
110+
if (Width != 0 && Height != 0)
111+
{
112+
destWidth = Width;
113+
destHeight = Height;
114+
}
115+
// change size proportially depending on width or height
116+
else if (Height != 0)
117+
{
118+
destWidth = (float)(Height * sourceWidth) / sourceHeight;
119+
destHeight = Height;
120+
}
121+
else
122+
{
123+
destWidth = Width;
124+
destHeight = (float)(sourceHeight * Width / sourceWidth);
125+
}
126+
127+
Bitmap bmPhoto = new Bitmap((int)destWidth, (int)destHeight,
128+
PixelFormat.Format32bppPArgb);
129+
bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);
130+
131+
Graphics grPhoto = Graphics.FromImage(bmPhoto);
132+
grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;
133+
134+
grPhoto.DrawImage(imgPhoto,
135+
new Rectangle(destX, destY, (int)destWidth, (int)destHeight),
136+
new Rectangle(sourceX, sourceY, (int)sourceWidth, (int)sourceHeight),
137+
GraphicsUnit.Pixel);
138+
139+
grPhoto.Dispose();
140+
141+
return bmPhoto;
142+
}
143+
}
144+
}

BookCollection/Models/Book.cs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,8 @@ public int MainAuthorID
9191
public int PublisherID { get; set; }
9292
public int MainSubjectID { get; set; }
9393

94+
public string ImageUrl { get; set; }
95+
9496
public virtual ICollection<Author> Authors { get; set; }
9597
public virtual Publisher Publisher { get; set; }
9698

BookCollection/Views/Books/Details.cshtml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
<div>
1111
<p>
1212
@BC.IconButton("Books", "Edit", "pencil", "Edit", new { id = Model.BookID })
13+
@BC.IconButton("Books", "UploadCover", "picture", "Upload book cover", new { id = Model.BookID })
1314
@BC.IconButton("Books", "Index", "th-list", "Back to List")
1415
</p>
1516
<hr />

BookCollection/Views/Books/Index.cshtml

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,9 @@
3232
</th>
3333
<th>
3434
@Html.ActionLink("Title", "Index", new { sortOrder = ViewBag.NameSortParm, currentFilter = ViewBag.CurrentFilter })
35+
36+
37+
<span class="glyphicon glyphicon-sort-by-alphabet" aria-hidden="true"></span>
3538
</th>
3639
<th>
3740
@Html.ActionLink("Author", "Index", new { sortOrder = ViewBag.AuthorSortParm, currentFilter = ViewBag.CurrentFilter })
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
2+
@{
3+
ViewBag.Title = "UploadCompleted";
4+
Layout = "~/Views/Shared/_Layout.cshtml";
5+
}
6+
7+
<h2>UploadCompleted</h2>
8+
9+
<p>
10+
@BC.IconButton("Books", "Index", "th-list", "Back to List")
11+
</p>
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
@model BookCollection.Models.Book
2+
3+
@{
4+
ViewBag.Title = "UploadCover";
5+
Layout = "~/Views/Shared/_Layout.cshtml";
6+
}
7+
8+
<p>
9+
@BC.IconButton("Books", "Edit", "pencil", "Edit", new { id = Model.BookID })
10+
@BC.IconButton("Books", "Index", "th-list", "Back to List")
11+
</p>
12+
<hr />
13+
<div class="row">
14+
<div class="col-md-12">
15+
<h2>Upload book cover for @Model.Title</h2>
16+
@if (ViewBag.Error != null)
17+
{
18+
<h4 style="color:red">@ViewBag.Error</h4>
19+
}
20+
@using (Html.BeginForm("UploadCover", "Home",
21+
FormMethod.Post, new { enctype = "multipart/form-data" }))
22+
{
23+
<div>Upload Image</div>
24+
@Html.HiddenFor(Model => Model.BookID)
25+
<input type="file" name="avatar" />
26+
<input type="submit" value="upload" />
27+
}
28+
</div>
29+
</div>

BookCollection/Views/Publishers/Details.cshtml

Lines changed: 1 addition & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -4,24 +4,14 @@
44
ViewBag.Title = "Publisher details";
55
}
66

7-
<h2>Publisher</h2>
7+
<h2>Publisher: @Html.DisplayFor(model => model.Name)</h2>
88

99
<div>
1010
<p>
1111
@BC.IconButton("Publishers", "Edit", "pencil", "Edit", new { id = Model.PublisherID })
1212
@BC.IconButton("Publishers", "Index", "th-list", "Back to List")
1313
</p>
1414
<hr />
15-
<dl class="dl-horizontal">
16-
<dt>
17-
@Html.DisplayNameFor(model => model.Name)
18-
</dt>
19-
20-
<dd>
21-
@Html.DisplayFor(model => model.Name)
22-
</dd>
23-
24-
</dl>
2515
</div>
2616

2717

0 commit comments

Comments
 (0)