文件上传MVC 4的问题 [英] Problems with a file upload MVC 4

查看:66
本文介绍了文件上传MVC 4的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在文件上传方面遇到了问题.这是我的控制器

 公共类StoreManagerController:控制器{私有StoreContext db = new StoreContext();//这里有一些动作////POST:/StoreManager/Create[HttpPost][ValidateAntiForgeryToken]公共ActionResult创建(书,HttpPostedFileBase文件){如果(ModelState.IsValid){book.CoverUrl = UploadCover(file,book.BookId);db.Books.Add(book);db.SaveChanges();返回RedirectToAction("Index");}ViewBag.AuthorId = new SelectList(db.Authors,"AuthorId","Name",book.AuthorId);ViewBag.GenreId =新的SelectList(db.Genres,"GenreId",名称",book.GenreId);ViewBag.PublisherId =新的SelectList(db.Publishers,"PublisherId","Name",book.PublisherId);返回View(book);}私有字符串UploadCover(HttpPostedFileBase文件,int id){字符串路径="/Content/Images/placeholder.gif";if(文件!=空&& file.ContentLength> 0){var fileExt = Path.GetExtension(file.FileName);如果(fileExt =="png" || fileExt =="jpg" || fileExt =="bmp"){var img = Image.FromStream(file.InputStream)作为位图;路径= Server.MapPath(〜/App_Data/Covers/")+ id +".jpg";img.Save(path,System.Drawing.Imaging.ImageFormat.Jpeg);}}返回路径;}} 

我的创建视图

  @using(Html.BeginForm("Create","StoreManager",FormMethod.Post,新{enctype ="multipart/form-data"})){@ Html.AntiForgeryToken()@ Html.ValidationSummary(true)@/*这里的divs */@< div class ="editor-label">覆盖</div>< div class ="editor-field">< input type ="file" name ="file" id ="file"/></div>< div class ="editor-label">@ Html.LabelFor(模型=>模型.描述)</div>< p><输入type ="submit" value =创建"/></p></fieldset> 

}

当我尝试上传文件时,我得到了一个默认的占位符.因此,我认为发布数据为空.但是当我用浏览器检查它时,我得到了下一个帖子数据

  ------ WebKitFormBoundary5PAA6N36PHLIxPJf内容处置:表单数据;name =文件";filename ="1.JPG"内容类型:图片/jpeg 

我在做什么错了?

解决方案

我首先看到的错误是有条件的:

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

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

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

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

如果仍然有问题,建议您在控制器操作中放置一个断点(您尚未指定这是 Edit 还是 Create 并检查该值是否 file 的大小符合预期.您应该能够找出问题出在哪里,并且-如果仍然无法解决-至少可以将问题范围缩小./p>

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?

解决方案

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.

这篇关于文件上传MVC 4的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆