有标记
<div>
@using (Html.BeginForm("Upload","Resume", FormMethod.Post, new { enctype = "multipart/form-data" }))
{ @Html.AntiForgeryToken() <fieldset> <legend>Download Resume</legend> <div class="editor-field">
@Html.TextBox("file", "", new { type = "file" }) </div> <div class="editor-field">
<input type="submit" value="Upload" style="width: 120px; height: 25px; font-size: 1.1em; padding:0" />
</div> </fieldset> }
</div>
和控制器:
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
try
{
if (file.ContentLength > 0) { var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/uploads"), fileName); file.SaveAs(path);
}
ViewBag.Message = "SuccessUpload";
return RedirectToAction("SuccessUpload", "Resume");
} catch
{ ViewBag.Message = "Fail";
return RedirectToAction("Upload"); }
}
如何在上传文件中生成唯一的文件名,谢谢你的答案!
答案 0 :(得分:8)
// change file name with its extension
var fileName = Guid.NewGuid().ToString() +
System.IO.Path.GetExtension(file.FileName);
var uploadUrl = Server.MapPath("~/uploads");
file.SaveAs(Path.Combine(uploadUrl, fileName));
答案 1 :(得分:6)
其中一种方法是结束当前日期。
var fileName = DateTime.Now.ToString("yyyymmddMMss") + System.IO.Path.GetExtension(file.FileName);