0

我在上传文件时遇到问题。这是我的控制器

    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

我究竟做错了什么?

4

1 回答 1

1

我能看到的第一件事是错误的,这是有条件的:

if (fileExt == "png" || fileExt == "jpg" || fileExt == "bmp")

这将永远不会返回true,因为Path.GetExtension包含一个“。” 在文件扩展名中。听起来这可能是您的主要问题,因为这只会跳过条件块,而您将留下占位符。这将需要更改为:

if (fileExt == ".png" || fileExt == ".jpg" || fileExt == ".bmp")

但是,您的问题中有太多代码,很难确定这是否是唯一的问题。

如果您仍然有问题,我建议在您的控制器操作中放置一个断点(您尚未指定这是EditCreate并检查的值是否file符合预期。您应该能够从那里隔离问题所在并且 -如果您仍然无法解决它 - 至少可以将您的问题缩小一点。

于 2013-05-12T12:53:08.757 回答