MVC上传文件功能
在提交数据的Controller控制器里:
public ActionResult SavePCNRequest(提交的Model类型 model, HttpPostedFileBase Attachment1)
{
//创建上传的路径
string PathValue = Server.MapPath("~/UploadFiles/xxx/" + model.ID + "/");
if (false == Directory.Exists(PathValue))
{
Directory.CreateDirectory(PathValue);
}
//获取是否有上传附件,有则进行上传
{
if (Attachment1 != null)
{
var fileName = Path.GetFileName(Attachment1.FileName);
if (fileName != "System.Web.HttpPostedFileWrapper")
{
model.Attachment1 = fileName;
}
//根据上传文件名生成新路径
var path = Path.Combine(PathValue, fileName);
Attachment1.SaveAs(path);
}
}
前端HTML页面代码:
<div class="form-group">
@Html.Label("Column Name for display", new { @class = "col-md-2 control-label" })
<div class="col-md-10">
<div class="col-md-8">
<input type="file" id="Attachment1" name="Attachment1" />
</div>
<div id="AddFileTemp1" class="col-md-4">
</div>
</div>
</div>