javascript - 在 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();
}
您还可以在文件名中添加当前日期时间:
newFileName= DateTime.Now.ToString("yyyyMMdd") + "-" + newName.Trim() + extension;
推荐阅读
- django-rest-framework - 如何在 django rest 框架中设置 arangodb
- amazon-web-services - EFS 卷绑定在 ECS 任务定义的每个“terraform apply”上自动分离/重新附加
- android - 尝试使用 vs 代码在真实设备上运行我的颤振应用程序
- android - Android - 合并使用前后摄像头拍摄的视频
- windows - 在 Windows bat 文件中获取 git 命令的输出
- windows - heroku 在 Windows 上打开“/.well-known/openid-configuration”错误
- javascript - 在下一个 js 中使用时正确输入 javascript
- powershell - Powershell - 参数的使用
- python - 通过 XPath 选择 h2 元素
- coq - 如何使用 coq 证明列表连接不可交换?