如何解决在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();
}
解决方法
从视图中将#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();
}
您还可以在文件名中添加当前的Datetime:
newFileName= DateTime.Now.ToString("yyyyMMdd") + "-" + newName.Trim() + extension;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。