想要将图像保存到文件夹并将URL保存在数据库中

时间:2021-07-13 00:23:12

I very newbie in asp.net mvc . here I had a problem in the controller image upload anyone can give help ?? This example controller I get from the internet , what should I change and code viewnya like, here I want to save the image through " AvatarUrl "

我是asp.net mvc的新手。在这里我有一个问题,在控制器图像上传任何人都可以给予帮助?我从互联网上获得的这个示例控制器,我应该更改和编码viewnya,这里我想通过“AvatarUrl”保存图像

Model > EmployeeServices

public class EmployeeModel{

    [ScaffoldColumn(false)]
    public int EmployeeID { get; set; }

    [Required(ErrorMessage = "Please Enter Position ID")]
    public int PositionID { get; set; }

    [Required(ErrorMessage = "Please Enter NO PEK")]
    public string NoPEK { get; set; }

    [Required(ErrorMessage = "Please Enter NO KTP")]
    public string NoKTP { get; set; }

    [Required(ErrorMessage = "Please Enter TaxID")]
    public string TaxID { get; set; }

    [Required(ErrorMessage = "Please Enter FirstName")]
    public string FirstName { get; set; }

    [Required(ErrorMessage = "Please Enter LastName")]
    public string LastName { get; set; }

    [Required(ErrorMessage = "Please Enter OrganizationID")]
    public int OrganizationID { get; set; }

    [Required(ErrorMessage = "Please Enter BirthPlace")]
    public string BirthPlace { get; set; }

    [Required(ErrorMessage = "Please Enter BirthDay")]
    public System.DateTime BirthDay { get; set; }

    [Required(ErrorMessage = "Please Enter Gender")]
    public string Gender { get; set; }

    [Required(ErrorMessage = "Please Enter Religion")]
    public string Religion { get; set; }

    [Required(ErrorMessage = "Please Enter TaxAddress")]
    public string TaxAddress { get; set; }

    [Required(ErrorMessage = "Please Enter Home Address")]
    public string HomeAddress { get; set; }

    [Required(ErrorMessage = "Please Enter Current Address")]
    public string CurrentAddress { get; set; }

    [Required(ErrorMessage = "Please Enter Phone Number")]
    public string PhoneNumber { get; set; }

    [Required(ErrorMessage = "Please Enter Email")]
    public string Email { get; set; }

    [Required(ErrorMessage = "Please Enter IsAuditor")]
    public string IsAuditor { get; set; }

    [Required(ErrorMessage = "Please Enter TaxProvince ")]
    public int TaxProvinceID { get; set; }

    [Required(ErrorMessage = "Please Enter Tax City ")]
    public int TaxCityID { get; set; }

    [Required(ErrorMessage = "Please Enter Home Province ")]
    public int HomeProvinceID { get; set; }

    [Required(ErrorMessage = "Please Enter Home City")]
    public int HomeCityID { get; set; }

    [Required(ErrorMessage = "Please Enter Current Province")]
    public int CurrentProvinceID { get; set; }

    [Required(ErrorMessage = "Please Enter Current City")]
    public int CurrentCityID { get; set; }

    [Required(ErrorMessage = "Please Enter Avatar Url")]
    public string AvatarUrl { get; set; }
}

Controller > EmployeesController

    [HttpPost]
    public ActionResult Create(EventModel eventmodel, HttpPostedFileBase file)
    {
        if (ModelState.IsValid)
        {
            var filename = Path.GetFileName(file.FileName);
            var path = Path.Combine(Server.MapPath("~/Uploads/Photo/"), filename);
            file.SaveAs(path);
            tyre.Url = filename;

            _db.EventModels.AddObject(eventmodel);
            _db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(eventmodel);
    }

2 个解决方案

#1


11  

Uploading a file, storing in the local file-system, and saving to a database is a common pattern. These are my recommendations.

上传文件,存储在本地文件系统中,并保存到数据库是一种常见的模式。这些是我的建议。

1. Do not use the uploaded filename as your filename.

1.不要使用上传的文件名作为文件名。

This is common:

这很常见:

var filename = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Uploads/Photo/"), filename);
file.SaveAs(path);

Don't do it. There are a few reasons:

不要这样做。有几个原因:

a) Filenames may conflict. b) Remote filenames may be incompatible with your local file-system. c) Someone may try a malicious filename and doing this may break your server.

a)文件名可能会发生冲突。 b)远程文件名可能与本地文件系统不兼容。 c)有人可能会尝试使用恶意文件名,这可能会破坏您的服务器。

Instead, generate your own filename (perhaps using a GUID, GUID.NewGuid().ToString()) and store the original filename in your database.

而是生成您自己的文件名(可能使用GUID,GUID.NewGuid()。ToString())并将原始文件名存储在您的数据库中。

2. Don't store all files in a single folder

2.不要将所有文件存储在单个文件夹中

At some point, your folder will contain too many files for the OS to process quickly.

在某些时候,您的文件夹将包含太多文件,操作系统无法快速处理。

Partition the files by something useful, like the user ID. This also helps to segregate the files between users.

通过有用的东西对文件进行分区,例如用户ID。这也有助于在用户之间隔离文件。

3. Don't store the full path to the file in the database

3.不要在数据库中存储文件的完整路径

At some point, you may move the files (perhaps to a different drive) and all your stored file locations will be broken.

在某些时候,您可能会移动文件(可能是另一个驱动器),并且所有存储的文件位置都将被破坏。

4. Don't store the image URL in the database

4.不要将图像URL存储在数据库中

Same as #3. If your web app changes and you want to change the image URLs, then you have incorrect URLs stored in the database. You'll have to scan and update all your database records.

与#3相同。如果您的Web应用程序发生更改并且您想要更改图像URL,那么您在数据库中存储的URL不正确。您必须扫描并更新所有数据库记录。

5. Don't store redundant path information in the database

5.不要在数据库中存储冗余路径信息

While it may be tempting to include "Uploads/Photo/" in the stored URL in the database, it has many problems too:

虽然在数据库中存储的URL中包含“Uploads / Photo /”可能很诱人,但它也存在许多问题:

a) It's redundant data. For every file, you're using extra, unnecessary, data space. b) If your app changes and the URL should change, your stored URLs are now broken.

a)这是冗余数据。对于每个文件,您都在使用额外的,不必要的数据空间。 b)如果您的应用更改并且URL应该更改,则您的存储的URL现在已损坏。

Instead, prepend "Uploads/Photo/" to the URL after you read the value from the database.

相反,在从数据库中读取值之后,将“Uploads / Photo /”添加到URL。

Update:

更新:

Here is some sample code:

以下是一些示例代码:

    [HttpPost]
    public ActionResult Create(EventModel eventmodel, HttpPostedFileBase file)
    {
        if (ModelState.IsValid)
        {
            var originalFilename = Path.GetFileName(file.FileName);
            string fileId = Guid.NewGuid().ToString().Replace("-", "");
            string userId = GetUserId(); // Function to get user id based on your schema

            var path = Path.Combine(Server.MapPath("~/Uploads/Photo/"), userId, fileId);
            file.SaveAs(path);

            eventModel.ImageId = fileId;
            eventmodel.OriginalFilename = originalFilename;

            _db.EventModels.AddObject(eventmodel);
            _db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(eventmodel);
    }

However, I would be wary about using your data model as the MVC action model.

但是,我会谨慎使用您的数据模型作为MVC操作模型。

#2


1  

You should change your AvatarUrl to:

您应该将AvatarUrl更改为:

public HttpPostedFileBase AvatarUrl { get; set; }

In your view, you can create a form similar to the following. Add the fields you will accept input for and use a file input for your avatar. When the form is posted back to the controller, MVC will attempt to bind the inputs to the parameters.

在您的视图中,您可以创建类似于以下的表单。添加您将接受输入的字段,并为您的头像使用文件输入。当表单回发到控制器时,MVC将尝试将输入绑定到参数。

@using(Html.BeginForm("Create", FormMethod.Post, new { enctype = "multipart/form-data" }) {
    <fieldset>
        @Html.LabelFor(m => m.FirstName)
        @Html.EditorFor(m => m.FirstName)
    </fieldset>
    <!--    
    REST OF YOUR INPUT FIELDS HERE
    -->
    <fieldset>
        @Html.LabelFor(m => m.Avatar)
        @Html.EditorFor(m => m.Avatar)
    </fieldset>
    <input type="submit" value="Submit" />
})

Your controller method should be updated to:

您的控制器方法应更新为:

[HttpPost]
public ActionResult Create(EmployeeModel model)
{
    if (ModelState.IsValid)
    {
        // Create avatar on server
        var filename = Path.GetFileName(model.AvatarUrl.FileName);
        var path = Path.Combine(Server.MapPath("~/Uploads/Photo/"), filename);
        file.SaveAs(path);
        // Add avatar reference to model and save
        model.AvatarUrl = string.Concat("Uploads/Photo/", filename);
        _db.EventModels.AddObject(model);
        _db.SaveChanges();

        return RedirectToAction("Index");
    }
    return View(model);
}

If you're still stuck let me know and I can go into more detail.

如果你仍然被卡住,请告诉我,我可以详细介绍。

There's also an excellent/detailed write up related to what you're trying to do here http://cpratt.co/file-uploads-in-asp-net-mvc-with-view-models/

还有一个很好的/详细的写作,与你在这里尝试做的有关http://cpratt.co/file-uploads-in-asp-net-mvc-with-view-models/

#1


11  

Uploading a file, storing in the local file-system, and saving to a database is a common pattern. These are my recommendations.

上传文件,存储在本地文件系统中,并保存到数据库是一种常见的模式。这些是我的建议。

1. Do not use the uploaded filename as your filename.

1.不要使用上传的文件名作为文件名。

This is common:

这很常见:

var filename = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Uploads/Photo/"), filename);
file.SaveAs(path);

Don't do it. There are a few reasons:

不要这样做。有几个原因:

a) Filenames may conflict. b) Remote filenames may be incompatible with your local file-system. c) Someone may try a malicious filename and doing this may break your server.

a)文件名可能会发生冲突。 b)远程文件名可能与本地文件系统不兼容。 c)有人可能会尝试使用恶意文件名,这可能会破坏您的服务器。

Instead, generate your own filename (perhaps using a GUID, GUID.NewGuid().ToString()) and store the original filename in your database.

而是生成您自己的文件名(可能使用GUID,GUID.NewGuid()。ToString())并将原始文件名存储在您的数据库中。

2. Don't store all files in a single folder

2.不要将所有文件存储在单个文件夹中

At some point, your folder will contain too many files for the OS to process quickly.

在某些时候,您的文件夹将包含太多文件,操作系统无法快速处理。

Partition the files by something useful, like the user ID. This also helps to segregate the files between users.

通过有用的东西对文件进行分区,例如用户ID。这也有助于在用户之间隔离文件。

3. Don't store the full path to the file in the database

3.不要在数据库中存储文件的完整路径

At some point, you may move the files (perhaps to a different drive) and all your stored file locations will be broken.

在某些时候,您可能会移动文件(可能是另一个驱动器),并且所有存储的文件位置都将被破坏。

4. Don't store the image URL in the database

4.不要将图像URL存储在数据库中

Same as #3. If your web app changes and you want to change the image URLs, then you have incorrect URLs stored in the database. You'll have to scan and update all your database records.

与#3相同。如果您的Web应用程序发生更改并且您想要更改图像URL,那么您在数据库中存储的URL不正确。您必须扫描并更新所有数据库记录。

5. Don't store redundant path information in the database

5.不要在数据库中存储冗余路径信息

While it may be tempting to include "Uploads/Photo/" in the stored URL in the database, it has many problems too:

虽然在数据库中存储的URL中包含“Uploads / Photo /”可能很诱人,但它也存在许多问题:

a) It's redundant data. For every file, you're using extra, unnecessary, data space. b) If your app changes and the URL should change, your stored URLs are now broken.

a)这是冗余数据。对于每个文件,您都在使用额外的,不必要的数据空间。 b)如果您的应用更改并且URL应该更改,则您的存储的URL现在已损坏。

Instead, prepend "Uploads/Photo/" to the URL after you read the value from the database.

相反,在从数据库中读取值之后,将“Uploads / Photo /”添加到URL。

Update:

更新:

Here is some sample code:

以下是一些示例代码:

    [HttpPost]
    public ActionResult Create(EventModel eventmodel, HttpPostedFileBase file)
    {
        if (ModelState.IsValid)
        {
            var originalFilename = Path.GetFileName(file.FileName);
            string fileId = Guid.NewGuid().ToString().Replace("-", "");
            string userId = GetUserId(); // Function to get user id based on your schema

            var path = Path.Combine(Server.MapPath("~/Uploads/Photo/"), userId, fileId);
            file.SaveAs(path);

            eventModel.ImageId = fileId;
            eventmodel.OriginalFilename = originalFilename;

            _db.EventModels.AddObject(eventmodel);
            _db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(eventmodel);
    }

However, I would be wary about using your data model as the MVC action model.

但是,我会谨慎使用您的数据模型作为MVC操作模型。

#2


1  

You should change your AvatarUrl to:

您应该将AvatarUrl更改为:

public HttpPostedFileBase AvatarUrl { get; set; }

In your view, you can create a form similar to the following. Add the fields you will accept input for and use a file input for your avatar. When the form is posted back to the controller, MVC will attempt to bind the inputs to the parameters.

在您的视图中,您可以创建类似于以下的表单。添加您将接受输入的字段,并为您的头像使用文件输入。当表单回发到控制器时,MVC将尝试将输入绑定到参数。

@using(Html.BeginForm("Create", FormMethod.Post, new { enctype = "multipart/form-data" }) {
    <fieldset>
        @Html.LabelFor(m => m.FirstName)
        @Html.EditorFor(m => m.FirstName)
    </fieldset>
    <!--    
    REST OF YOUR INPUT FIELDS HERE
    -->
    <fieldset>
        @Html.LabelFor(m => m.Avatar)
        @Html.EditorFor(m => m.Avatar)
    </fieldset>
    <input type="submit" value="Submit" />
})

Your controller method should be updated to:

您的控制器方法应更新为:

[HttpPost]
public ActionResult Create(EmployeeModel model)
{
    if (ModelState.IsValid)
    {
        // Create avatar on server
        var filename = Path.GetFileName(model.AvatarUrl.FileName);
        var path = Path.Combine(Server.MapPath("~/Uploads/Photo/"), filename);
        file.SaveAs(path);
        // Add avatar reference to model and save
        model.AvatarUrl = string.Concat("Uploads/Photo/", filename);
        _db.EventModels.AddObject(model);
        _db.SaveChanges();

        return RedirectToAction("Index");
    }
    return View(model);
}

If you're still stuck let me know and I can go into more detail.

如果你仍然被卡住,请告诉我,我可以详细介绍。

There's also an excellent/detailed write up related to what you're trying to do here http://cpratt.co/file-uploads-in-asp-net-mvc-with-view-models/

还有一个很好的/详细的写作,与你在这里尝试做的有关http://cpratt.co/file-uploads-in-asp-net-mvc-with-view-models/