webapi 实现上传图片到服务器端并返回路径

单图片上传:

  1. 通过HttpContext.Current.Request.Files来接收前端传过来的数据;
  2. SaveAs保存到指定文件夹下;
/// <summary>
/// 上传图片
/// </summary>
/// <returns>返回图片路径</returns>
[HttpPost]
public ApiResult UploadImage()
{
      HttpFileCollection files = HttpContext.Current.Request.Files;
      if (files.Count > 0 && files[0].ContentLength > 0)
      {
            string goodsPath = "";
            string txtGuid = Guid.NewGuid().ToString("N");//生成guid
            string thisUrl = "http://192.168.6.66:44392";
            goodsPath = "/Upload/Goods/" + DateTime.Now.ToString("yyyyMMddHHmmss") + "_" + txtGuid.Substring(txtGuid.Length - 6) + "_" + Path.GetFileName(files[0].FileName);
            files[0].SaveAs(HttpContext.Current.Server.MapPath(goodsPath));//保存到指定文件夹
            result.setApiResult(200, "SUCCESS", "SUCCESS", thisUrl+goodsPath);
      }
      else
      {
            result.setApiResult(400, "PICTURE_ERROR", "上传图片不存在");
      }
      return result;
}
上一篇:WebApi 接口返回值类型详解 ( 转 )


下一篇:Asp.Net WebApi接口返回值IHttpActionResult