Problems with a file upload MVC 4

2019-08-30 02:23发布

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?

1条回答
贪生不怕死
2楼-- · 2019-08-30 03:19

The first thing I can see that is wrong is this conditional:

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

This will never return true, because Path.GetExtension includes a '.' in the file extension. It sounds like this might be your main problem as this will simply skip the conditional block and you'll be left with your placeholder. This will need to be changed to:

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

However, there is so much code in your question that it's difficult to determine whether this is the only problem.

If you still have problems, I would suggest placing a breakpoint in your controller action (you haven't specified whether this is Edit or Create and checking whether the value of file is as expected. You should be able to isolate where the problem is from there and - if you still can't resolve it - will at least be able to narrow your question down a bit.

查看更多
登录 后发表回答