2013-07-25 123 views
1

我想使用ajax上傳圖片。我發送的請求是這樣的:使用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。 感謝

回答

0

我不使用MVC,但如果你想使用阿賈克斯$那麼這裏是......

$('.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."); 
     } 
    }