使用htmlcontrol在c#中使用webservices上传图像

时间:2016-09-07 09:06:10

标签: c# web-services

 [WebMethod(EnableSession = true)]
     public int InsertBannerImages(string OwnerID,DateTime StrtDt,DateTime Enddt,string filename,string Zip)
     {
         
         HttpPostedFile file = HttpContext.Current.Request.Files[filename];
         string fileExtension = Path.GetExtension(filename);
         string filePath = "/Banner/" + OwnerID + "/BannerImages/" + Zip + file + "_banner" + fileExtension;
         string strfilelocation = "/Banner/" + OwnerID + "/BannerImages/";
         if (!Directory.Exists(strfilelocation))
         {
             Directory.CreateDirectory(Server.MapPath(strfilelocation));
         }
         if (!Directory.Exists(filePath))
         {
             Directory.CreateDirectory(Server.MapPath(filePath));
         }
         
         int res = objbanner.InsertBannerUpload();
         return res;
     }

我正在尝试使用web-service上传图像,其中文件上传控件是html文件上传。但我无法将图像保存在我的应用程序文件夹中

HttpPostedFile file = HttpContext.Current.Request.Files[filename];
string fileExtension = Path.GetExtension(filename);
string filePath = "/Banner/" + OwnerID + "/BannerImages/" + Zip + file + "_banner" + fileExtension;
string strfilelocation = "/Banner/" + OwnerID + "/BannerImages/";

if (!Directory.Exists(strfilelocation))
{
    Directory.CreateDirectory(Server.MapPath(strfilelocation));
}

if (!Directory.Exists(filePath))
{
    Directory.CreateDirectory(Server.MapPath(filePath));
}

其中filename只是图像名称EX:hello.jpg

1 个答案:

答案 0 :(得分:0)

首先我们需要从html中的表单中获取所有文件,然后使用ajax调用Web服务,如下所示

var data = new FormData();
var files = $("#uploadcntrlid").get(0).files;

// Add the uploaded image content to the form data collection

if (files.length > 0) {  
   data.append("ImageFiles", files[0]);
}  

// Make Ajax request with the contentType = false, and procesDate = false
var ajaxRequest = $.ajax({  
      type: "POST",
      url: "fileupload.asmx/uploadfile",
      contentType: false,
      processData: false,
      data: data
   });

内部网络服务(.asmx或任何)

[WebMethod]
public void uploadfile()
{
    var imgFiles = HttpContext.Current.Request.Files["ImageFiles"];
    foreach (string key in imgFiles)
    {
       HttpPostedFile file = imgFiles[key];
       string fileName = file.FileName;
       var fileSavePath = Path.Combine(HttpContext.Current.Server.MapPath("~/ImageFiles"), fileName);
       file.SaveAs(fileSavePath);
     }
}