以下是代码的实现过程:
Html页面表单布局:
1 <form id="UpPicture" enctype="multipart/form-data" action="服务器路径地址" method="post"> 2 <table> 3 <tr> 4 <td> 5 <input type="file" name="Picture"/> 6 </td> 7 </tr> 8 9 <tr> 10 <td>提交</td> 11 <td> 12 <input type="submit" value="提交" /></td> 13 </tr> 14 </table> 15 </form>
服务器端是实现:
1 /// <summary> 2 /// 图片上传方法,客户端通过表单的形式上传 3 /// </summary> 4 /// <returns></returns> 5 [HttpPost] 6 public PhotographUploadReturn PhotographUpload() 7 { 8 var msg = ""; 9 string _toServerPicturePath = "";//文件名 10 //接收表单传递过来的图片,需要限定上传的图片格式:".JPG", ".JPEG", ".GIF", ".PNG", ".BMP" 11 var file = HttpContext.Current.Request.Files["Picture"]; 12 13 //检查文件是否被预览选中,判断方式:通过判断文件名是否为空或者空字符串 14 if (!string.IsNullOrWhiteSpace(file.FileName)) 15 { 16 //限定上传图片的格式类型 17 string[] LimitPictureType = { ".JPG", ".JPEG", ".GIF", ".PNG", ".BMP" }; 18 //当图片上被选中时,拿到文件的扩展名 19 string currentPictureExtension = Path.GetExtension(file.FileName).ToUpper(); 20 //此处对图片上传的类型进行限定操作 21 if (LimitPictureType.Contains(currentPictureExtension)) 22 { 23 //此处标记图片上传至服务器的唯一新名称 24 string _newFileName = Guid.NewGuid().ToString(); 25 _toServerPicturePath = DateTime.Now.Year + "/" + DateTime.Now.Month + "/"; 26 string _dbPicturePath = "Certifications/" + _toServerPicturePath + _newFileName + currentPictureExtension; 27 _toServerPicturePath = AppDomain.CurrentDomain.BaseDirectory + "Certifications/" + _toServerPicturePath;//最终生成的文件名:+_newFileName +currentPictureExtension 28 29 //首先判断图片上传至服务的路径是否存在,不存在则创建并执行保存操作,存在则直接保存 30 if (Directory.Exists(_toServerPicturePath)) 31 { 32 //最终上传的文件路径全名 33 _toServerPicturePath = _toServerPicturePath + _newFileName + currentPictureExtension; 34 } 35 else 36 {//不存在此路径,则创建后执行保存操作 37 Directory.CreateDirectory(_toServerPicturePath); 38 _toServerPicturePath = _toServerPicturePath + _newFileName + currentPictureExtension; 39 } 40 //执行保存图片,并插入数据库操作 41 file.SaveAs(HttpContext.Current.Server.MapPath("~/" + _dbPicturePath)); 42 ////执行数据库相关操作,没有异常则代码继续执行,否则跳出 43 msg = "图片上传操作成功!"; 44 } 45 else 46 { 47 msg = "图片上传操作失败,请选择扩展名为:.JPG, .JPEG, .GIF, .PNG, .BMP 等类型图片。"; 48 } 49 } 50 else 51 { 52 msg = "图片上传操作失败,图片没有被选中!"; 53 } 54 55 return new PhotographUploadReturn { ImageName = _toServerPicturePath, Message = msg }; 56 }