简体   繁体   English

在 ASP.net MVC 3 C# 中保存来自 HTML 表单的图像

[英]Saving an image from HTML form in ASP.net MVC 3 C#

I'm hoping someone can modify my code below to show me exactly how to get this to do what I want.我希望有人可以在下面修改我的代码,以准确地向我展示如何让它做我想做的事。

I have an HTML form that posts to the following action:我有一个 HTML 表单,可以发布到以下操作:

public ActionResult Create(string EntryTitle, string EntryVideo, HttpPostedFileBase ImageFile, string EntryDesc)
    {
        if (Session["User"] != null)
        {
            User currentUser = (User)Session["User"];

            string savedFileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Path.GetFileName(ImageFile.FileName)); 
            ImageFile.SaveAs(savedFileName);

            Entry newEntry = new Entry();

            newEntry.Title = EntryTitle;
            newEntry.EmbedURL = EntryVideo;
            newEntry.Description = EntryDesc;
            newEntry.ImagePath = savedFileName;
            newEntry.UserId = currentUser.UserId;

            db.Entries.Add(newEntry);
            db.SaveChanges();


        }

        return RedirectToAction("MyPage", "User");
    }

This saves the image to the root solution directory (or tries to, doesn't have permission and throws exception instead).这会将图像保存到根解决方案目录(或试图,没有权限并抛出异常)。

What I would like it to do is the following:我希望它做的是:

1.) Verify that the file size is under some maximum, let's say 500kb for now 1.) 验证文件大小是否低于某个最大值,假设现在为 500kb

2.) Assuming file size is okay, save it to the following directory 2.) 假设文件大小没问题,将其保存到以下目录

mywebsite.com/uploads/<userid>/<entryid>/entry-image.<jpg/png/gif>

I'm not sure how to rename the file since I want to accept different file extensions (.jpeg, .jpg, .png, .gif).我不确定如何重命名文件,因为我想接受不同的文件扩展名(.jpeg、.jpg、.png、.gif)。 Or unsure how to get it into the correct directory like above.或者不确定如何将它放入上面的正确目录中。 Or how to validate file size, since apparently you can only do that with javascript if the user is using IE.或者如何验证文件大小,因为如果用户使用 IE,显然你只能使用 javascript 来验证文件大小。

1.Verify that the file size is under some maximum, let's say 500kb for now 1.验证文件大小是否低于某个最大值,假设现在为 500kb

You can use the HttpPostFileBase.ContentLength property to get the size (in bytes) of the file.您可以使用HttpPostFileBase.ContentLength属性获取文件的大小(以字节为单位)。

if (ImageFile.ContentLength > 1024 * 500) // 1024 bytes * 500 == 500kb
{
    // The file is too big.
}

2.Assuming file size is okay, save it to the following directory 2.假设文件大小没问题,保存到如下目录

string savedFileName = Server.MapPath(string.Format("~/uploads/{0}/{1}/entry-image{2}",
    currentUser.UserId,
    newEntry.EntryId,
    Path.GetExtension(ImageFile.FileName)));

The only problem I see is that it looks like your Entry.EntryId might be generated at the database so you won't be able to use it as part of the save path until it's been generated.我看到的唯一问题是,您的 Entry.EntryId 看起来可能是在数据库中生成的,因此在生成之前您将无法将其用作保存路径的一部分。

hope this helps or at least points you in the right direction希望这有助于或至少为您指明正确的方向

    if (ImageFile.ContentLength < 1024 * 500)
            {
                Entry newEntry = new Entry();

                newEntry.Title = EntryTitle;
                newEntry.EmbedURL = EntryVideo;
                newEntry.Description = EntryDesc;
                newEntry.UserId = currentUser.UserId;

                db.Entries.Add(newEntry);
                db.SaveChanges();  //this helps generate an entry id

                string uploadsDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "uploads");
                string userDir = Path.Combine(uploadsDir, <userid>);
                string entryDir = Path.Combine(userDir, newEntry.EntryID );

                if (Directory.Exists(userDir) == false)
                    Directory.CreateDirectory(userDir);

                if (Directory.Exists(entryDir) == false)
                    Directory.CreateDirectory(entryDir);

               string savedFileName = Path.Combine(entryDir, <entry-image>);
               ImageFile.SaveAs(savedFileName);

               newEntry.ImagePath = savedFileName;  //if this doesn't work pull back out this entry and adjust the ImagePath
               db.SaveChanges();

            }

You should grant a write permission to the 'uploads' directory.您应该授予对“上传”目录的写权限。

you can also limit file sizes for your web app from the web.config您还可以通过 web.config 限制 web 应用程序的文件大小

    <system.web>
       <httpRuntime   maxRequestLength="500"/>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM