I had a problem with file upload. Here is my controller
public class StoreManagerController : Controller
{
private StoreContext db = new StoreContext();
//Some actions here
//
// POST: /StoreManager/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Book book, HttpPostedFileBase file)
{
if (ModelState.IsValid)
{
book.CoverUrl = UploadCover(file, book.BookId);
db.Books.Add(book);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.AuthorId = new SelectList(db.Authors, "AuthorId", "Name", book.AuthorId);
ViewBag.GenreId = new SelectList(db.Genres, "GenreId", "Name", book.GenreId);
ViewBag.PublisherId = new SelectList(db.Publishers, "PublisherId", "Name", book.PublisherId);
return View(book);
}
private string UploadCover(HttpPostedFileBase file, int id)
{
string path = "/Content/Images/placeholder.gif";
if (file != null && file.ContentLength > 0)
{
var fileExt = Path.GetExtension(file.FileName);
if (fileExt == "png" || fileExt == "jpg" || fileExt == "bmp")
{
var img = Image.FromStream(file.InputStream) as Bitmap;
path = Server.MapPath("~/App_Data/Covers/") + id + ".jpg";
img.Save(path, System.Drawing.Imaging.ImageFormat.Jpeg);
}
}
return path;
}
}
My Create View
@using (Html.BeginForm("Create", "StoreManager", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
@/* divs here */@
<div class="editor-label">
Cover
</div>
<div class="editor-field">
<input type="file" name="file" id="file"/>
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Description)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
When I try upload a file, I got a default placeholder. So I think the post data is null. But when I inspected it with browser I got the next post data
------WebKitFormBoundary5PAA6N36PHLIxPJf
Content-Disposition: form-data; name="file"; filename="1.JPG"
Content-Type: image/jpeg
What am I doing wrong?