我在上传文件时遇到问题。这是我的控制器
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;
}
}
我的创建视图
@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>
}
当我尝试上传文件时,我得到了一个默认占位符。所以我认为帖子数据为空。但是当我用浏览器检查它时,我得到了下一个帖子数据
------WebKitFormBoundary5PAA6N36PHLIxPJf
Content-Disposition: form-data; name="file"; filename="1.JPG"
Content-Type: image/jpeg
我究竟做错了什么?