简单上传图片代码
using System.IO;
public string UpdatePic(HttpPostedFileBase pic) { string filePath = null; string filename = null; try { string path = Server.MapPath("~/Upload/"); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } filename = pic.FileName;//获得文件上传全目录 //filename = DateTime.Now.ToString("yyyyMMddHHmmssfff"); int place = filename.LastIndexOf(".") + 1;//获得文件扩展名的位置 string extname = filename.Substring(place).ToLower();//得到文件扩展名 string allowedType = "jpg|bmp|jpeg|psd|png";//允许上传文件类型 long allowedSize = 512000 * 1024;//允许上传最大文件大小 if (allowedType.Contains(extname) && pic.ContentLength < allowedSize) { filePath = path + filename; pic.SaveAs(filePath); } else { return null; } } catch (Exception err) { throw new Exception(err.Message); } return filename; }
HttpPostedFileBase file = Request.Files["pic"]; if (file.ContentLength != 0) { string filename = UpdatePic(file); model.Url = @"..\..\Upload\" + filename; }
<tr> <th>@Html.LabelFor(model=>model.Url)</th> <td> <input type="file" name="pic" id="pic" /> </td> </tr>
@using (Html.BeginForm("AddActivity", "Activity", FormMethod.Post, new { enctype = "multipart/form-data"}))
这种方法兼容性不好,不建议使用,建议使用 Uploadify插件,参考 http://www.cnblogs.com/yechangzhong-826217795/p/3785842.html