简体   繁体   English

在 ASP.NET MVC 中上传和更改图像的新名称

[英]Upload and change a new name for image in ASP.NET MVC

I want, when uploading an image after that I will enter a new name for image and after press submit then the image will be changed the new name and it will be saved in path of project, please guide me how to write code ?我想,之后上传图像时,我将为图像输入一个新名称,然后按提交后图像将更改为新名称并将其保存在项目路径中,请指导我如何编写代码? many thanks非常感谢

enter code here在此处输入代码

    <div class="row">
        <div class="col-sm-6">
            Image Name: <input type="text" id="name"/>

            <input type="file" class="form-control" id="files" name="files">

            <input type=submit/>
        </div>
    </div>

code:代码:

public ActionResult UploadFiles(HttpPostedFileBase files) {公共 ActionResult 上传文件(HttpPostedFileBase 文件){

        string newFileName = "";

        if (files != null)
        {
            string path = HttpContext.Server.MapPath(@"~/Data/images");

            bool exists = Directory.Exists(path);

            if (!exists)
                Directory.CreateDirectory(path);

            string extension = Path.GetExtension(files.FileName);
            newFileName = Guid.NewGuid() + extension;
            string filePath = Path.Combine(path, newFileName);
            files.SaveAs(filePath);

        }
        return View();
    }

From view pass #name value into the controller method UploadFiles along with the files in form of parameters.从视图中将#name 值与参数形式的文件一起传递到控制器方法 UploadFiles 中。

Controller:控制器:

public ActionResult UploadFiles(HttpPostedFileBase files, string newName) {

        string newFileName = "";

        if (files != null)
        {
            string path = HttpContext.Server.MapPath(@"~/Data/images");

            bool exists = Directory.Exists(path);

            if (!exists)
                Directory.CreateDirectory(path);

            string extension = Path.GetExtension(files.FileName);
            newFileName = newName.Trim() + extension; //pass newName here
            string filePath = Path.Combine(path, newFileName);
            files.SaveAs(filePath);

        }
        return View();
    }

You can also add current Datetime in file name:您还可以在文件名中添加当前日期时间:

newFileName= DateTime.Now.ToString("yyyyMMdd") + "-" + newName.Trim() + extension;

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

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