C# code[AcceptVerbs(HttpVerbs.Post)]
public ContentResult Upload(HttpPostedFileBase FileData, string folder) {
string result = "";
if (null != FileData) {
try {
if (PathHelper.CheckFileName(FileData.FileName) == false) throw new ApplicationException();
result = Path.GetFileName(FileData.FileName);//获得文件名
//string ext = Path.GetExtension(FileData.FileName);//获得文件扩展名
//string saveName = "uploadfile" + ext;//实际保存文件名
saveFile(FileData, folder, result);//保存文件
Logger.Instance.Info(this, "Upload", string.Format("上传文件{0}成功", result));
} catch (Exception ex) {
result = ex.ToString();
Logger.Instance.Warn(this, "Upload", "上传文件失败,错误信息为:" + ex.ToString());
}
}
return Content(result);
}
[Authorize]
[RoleFilter(checkRole = "1")]
[NonAction]
private void saveFile(HttpPostedFileBase postedFile, string filepath, string saveName) {
filepath = filepath.Substring(6, filepath.Length - 6);
if (!Directory.Exists(filepath)) {
Directory.CreateDirectory(filepath);
}
try {
postedFile.SaveAs(Path.Combine(filepath, saveName));
Logger.Instance.Info(this, "saveFile", string.Format("保存文件{0}成功", Path.Combine(filepath, saveName)));
} catch (Exception e) {
Logger.Instance.Warn(this, "saveFile", "保存文件失败,错误信息为:" + e.ToString());
throw new ApplicationException(e.Message);
}
}