你可以写一个asp.net mvc 根据下拉框不同的值将不同类型的文件存在本地文件夹里,若下拉框未选择会弹出提示的代码例子吗 
时间: 2023-06-06 15:07:38 浏览: 27
当然可以,下面是一个简单的ASP.NET MVC的代码例子:
Controller代码:
```
public class FileController : Controller
{
private readonly string _baseFolder = @"C:\Files\";
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Upload(UploadViewModel model)
{
if (model.SelectedFileType == FileType.None)
{
ModelState.AddModelError(nameof(model.SelectedFileType), "Please select a file type");
}
if (model.File == null || model.File.ContentLength == 0)
{
ModelState.AddModelError(nameof(model.File), "Please select a file");
}
if (!ModelState.IsValid)
{
return View("Index", model);
}
var fileName = $"{model.SelectedFileType}_{DateTime.Now:yyyyMMddHHmmss}{Path.GetExtension(model.File.FileName)}";
var fullPath = Path.Combine(_baseFolder, fileName);
model.File.SaveAs(fullPath);
ViewBag.Message = "File uploaded successfully";
return View("Index");
}
}
```
View代码:
```
@model UploadViewModel
@{
ViewBag.Title = "Upload";
}
<h2>Upload a file</h2>
@using (Html.BeginForm("Upload", "File", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.ValidationSummary(true)
<div class="form-group">
@Html.LabelFor(m => m.SelectedFileType)
@Html.DropDownListFor(m => m.SelectedFileType, new SelectList(Enum.GetValues(typeof(FileType))), "- Select -", new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.SelectedFileType)
</div>
<div class="form-group">
@Html.LabelFor(m => m.File)
<input type="file" name="file" class="form-control" />
@Html.ValidationMessageFor(m => m.File)
</div>
<button type="submit" class="btn btn-primary">Upload</button>
}
@if (ViewBag.Message != null)
{
<div class="alert alert-success">@ViewBag.Message</div>
}
@section scripts {
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.2/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validation-unobtrusive/3.2.11/jquery.validate.unobtrusive.min.js"></script>
}
```
ViewModel代码:
```
public class UploadViewModel
{
[Required(ErrorMessage = "Please select a file type")]
public FileType SelectedFileType { get; set; }
[Required(ErrorMessage = "Please select a file")]
[FileSize(1024 * 1024 * 10, ErrorMessage = "File size cannot exceed 10MB")]
[FileTypes("txt,pdf,doc,docx,xls,xlsx,jpg,jpeg,png,gif", ErrorMessage = "File type is not supported")]
public HttpPostedFileBase File { get; set; }
}
public enum FileType
{
None,
Text,
Image,
Document,
Spreadsheet
}
```
其中,FileType是一个枚举,表示不同类型的文件,例如Text表示文本文件,Image表示图像文件等。而FileSize和FileTypes是自定义的Validation Attribute,用于限制文件大小和文件类型。需要注意的是,由于涉及到文件上传,为了保证安全性,最好在IIS上将根目录设置为只读。
相关推荐











