首页 > 解决方案 > 在 ASP.NET MVC 中上传和更改图像的新名称

问题描述

我想,在上传图片之后,我会输入一个新的图片名称,然后按提交后,图片将更改为新名称,并将保存在项目路径中,请指导我如何编写代码?非常感谢

在此处输入代码

    <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>

代码:

公共 ActionResult UploadFiles(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();
    }

标签: javascriptc#asp.netasp.net-mvc

解决方案


从视图中将#name 值与参数形式的文件一起传递给控制器​​方法 UploadFiles。

控制器:

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();
    }

您还可以在文件名中添加当前日期时间:

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

推荐阅读