1

我正在尝试使用 ajax 上传图片。我正在发送这样的请求:

@using (Ajax.BeginForm("SaveReferral", "ReferralIM", new AjaxOptions
{
    HttpMethod = "POST",
    OnSuccess = "OnSuccessReferralSent"
}, new { id = "frmReferral", onSubmit = "OnControlMapping(this);" }))
{

}

如果我这样发送请求:

 @using (Html.BeginForm("SaveReferral", "ReferralIM", FormMethod.Post, new { id = "frmReferral", enctype = "multipart/form-data" }))
   { 

文件上传成功,但我想使用 ajax,请帮助我如何使用 ajax 上传文件。谢谢

4

1 回答 1

-1

我没有使用 MVC,但如果你想使用 $.ajax 那么这里是......

$('.file-uploadID').on('click', function (e) {
            e.preventDefault();
            var fileInput = $('.file-uploadID');
            var fileData = fileInput.prop("files")[0];   // Getting the properties of file from file field
            formData.append("file", fileData); // Appending parameter named file with properties of file_field to form_data
            formData.append("user_email", email); //adding email address as parameter if you have
            $.ajax({
                  url: '/FileUploadHandler.ashx',
                  data: formData,
                  processData: formData.processData,
                  contentType: formData.contentType,
                  type: 'POST',
                  success: function (data) {
                        var obj = $.parseJSON(data);
                        if (obj.StatusCode == "OK") {
                              alert("file upload done");
                        } else if (obj.StatusCode == "ERROR") {
                              alert("file upload error");
                        }
                  },
                  error: function (errorData) {
                        $('.result-message').html("There was a problem uploading the file. Please try again.").show();
                  }
            });
      }); 

处理程序

public void ProcessRequest(HttpContext context)
  {
        context.Response.ContentType = "text/plain";
        context.Response.Expires = -1;
        var email = context.Request.Params["user_email"];
        var fileData = context.Request.Files["file"];
        try
        {
             var result =  UploadImageToServer(email, fileData);
              context.Response.Write(result);
        }
        catch (Exception ex)
        {
              context.Response.Write("error while uploading file to the server, please try again.");
        }
  }
于 2013-07-25T13:06:37.730 回答