MVC下 服务端代码:
[HttpPost] public ActionResult UploadImg(string types) {string data = ""; try { if (types == "image") { foreach (string f in Request.Files.AllKeys) { string pathT = HttpRuntime.AppDomainAppPath.ToString() + "/UpLoadImages/"; string pathD = DateTime.Now.ToString("yyyyMMdd") + "/" + DateTime.Now.ToString("HHmm") + "/"; string sPath = pathT + pathD; if (!Directory.Exists(sPath)) { Directory.CreateDirectory(sPath); } HttpPostedFileBase file = Request.Files[f]; Random seed = new Random(); int randomNum = seed.Next(10, 99); string fileName = DateTime.Now.ToString("HHmmss") + randomNum.ToString() + ".jpg"; file.SaveAs(sPath + fileName); string ImgStr = sPath + fileName; data = "{"Code":"10000","Message":"" + ImgStr + ""}"; } } else { data = "{"Code":"-10000","Message":"上传格式不正确"}"; } } catch (Exception ex) { data = "{"Code":"-10000","Message":"" + ex.Message + ""}"; } return Content(data, "application/json"); }
客户端代码: UpLoadImage.aspx
public partial class UpLoadImage : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { WebClient webclient = new WebClient(); string fileName = @"C:UsersadminDesktop om2.jpg"; byte[] responseArray = webclient.UploadFile("http://localhost:8987/Home/UploadImg?types=image", "POST", fileName); string getPath = Encoding.GetEncoding("UTF-8").GetString(responseArray); Response.Write(getPath); } }