如何通过Ajax从C#接收文件

时间:2018-11-26 19:45:38

标签: c# asp.net ajax webmethod

我正在尝试通过ajax发送文件,并且无法保存它,有人来帮助我,我已经尝试了几个序列化但没有一个有效。我向您展示了客户端代码和服务器端,如果我做对了或者[webmethod]还有另一种方法可以帮到您,这对您很有帮助

$("#btnCargar").on("click", function() {
  var filese = $("#fileComparendo")[0].files[0];
  var formData = new FormData();
  formData.append("archivo", filese);

  $.ajax({
    type: "POST",
    url: "<%=ResolveUrl("addcomp.aspx/prueba")%>",
    data: formData,
    contentType: false,
    processData: false,

    success: function(data) {
      alert(data);
      console.log("CallWM" + data.d);
      alert(data.d);
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
      var err = eval("(" + XMLHttpRequest.responseText + ")");
      alert(err.Message)
      console.log("Ajax Error!");
    }
  });

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div class="row">
  <div class="col-md-4">
    <input type="text" id="txtPrueba" class="form-contrav" />
    <input type="file" class="file-name" id="fileComparendo" />
    <input type="button" class="btn btn-danger" value="Cargar" id="btnCargar" />
  </div>
</div>

[WebMethod]
public static  string prueba(HttpContext archivo)
{
   // var recipient = Request["Recipient"];
    var re =  HttpContext.Current.Request.Form["archivo"];
    archivo.Response.ContentType = "text/plain";

    string dirFullPath = HttpContext.Current.Server.MapPath("~/files/");
    string[] files;
    int numFiles;
    files = System.IO.Directory.GetFiles(dirFullPath);
    numFiles = files.Length;
    numFiles = numFiles + 1;
    string str_image = "";
    foreach (string s in archivo.Request.Files)
    {
        HttpPostedFile file = archivo.Request.Files[s];
        string fileName = file.FileName;
        string fileExtension = file.ContentType;

        if (!string.IsNullOrEmpty(fileName))
        {
            fileExtension = Path.GetExtension(fileName);
            str_image = "MyPHOTO_" + numFiles.ToString() + fileExtension;
            string pathToSave_100 = HttpContext.Current.Server.MapPath("~/files/") + str_image;
            file.SaveAs(pathToSave_100);
        }
    }
    archivo.Response.Write(str_image);
    return "hola";
}

1 个答案:

答案 0 :(得分:0)

[WebMethod]只能接受application / json的内容类型,但是您可以使用.ashx:https://stackoverflow.com/a/26273565/1429439

添加一个名为Upload.ashx的新通用处理程序,然后将ProcessRequest()替换为:

public void ProcessRequest(HttpContext archivo)
        {
            var re = HttpContext.Current.Request.Form["archivo"];
            archivo.Response.ContentType = "text/plain";

            string dirFullPath = HttpContext.Current.Server.MapPath("~/files/");
            string[] files;
            int numFiles;
            files = System.IO.Directory.GetFiles(dirFullPath);
            numFiles = files.Length;
            numFiles = numFiles + 1;
            string str_image = "";
            foreach (string s in archivo.Request.Files)
            {
                HttpPostedFile file = archivo.Request.Files[s];
                string fileName = file.FileName;
                string fileExtension = file.ContentType;

                if (!string.IsNullOrEmpty(fileName))
                {
                    fileExtension = System.IO.Path.GetExtension(fileName);
                    str_image = "MyPHOTO_" + numFiles.ToString() + fileExtension;
                    string pathToSave_100 = HttpContext.Current.Server.MapPath("~/files/") + str_image;
                    file.SaveAs(pathToSave_100);
                }
            }
            archivo.Response.Write(str_image);
        }

使用以下命令更新$.ajax()中的网址以指向Upload.ashx

url: "<%=ResolveUrl("Upload.ashx")%>",