Peter Liaros
Peter Liaros

Reputation: 161

Pass file input from AJAX to C# WebMethod

There are a few solutions floating around, however none seem to work for me.

I have a File Input as per the below: (Bootstrap File Input)

<div class="fileinput fileinput-new" data-provides="fileinput">
   <div class="fileinput-new thumbnail" style="width: 200px; height: 150px;">
      <img src="http://www.placehold.it/200x150/EFEFEF/AAAAAA&amp;text=no+image" alt=""/>
   </div>
   <div class="fileinput-preview fileinput-exists thumbnail" style="max-width: 200px; max-height: 150px;">
   </div>
   <div>
      <span class="btn default btn-file">
         <span class="fileinput-new">
            Select image
         </span>
         <span class="fileinput-exists">
           Change
         </span>
         <input type="file" id="image" runat="server" accept=".gif|.jpeg|.jpg|.png" />
      </span>
      <a href="#" class="btn default fileinput-exists" data-dismiss="fileinput">
         Remove
      </a>
      <a onclick="uploadImage();" class="btn blue fileinput-exists">Upload Image</a>
    </div>
 </div>

Upon selecting an image, and clicking 'Upload Image', the following JS function is run:

 function uploadImage() {
    var file = $("#image")[0].files[0];
    var name = file.name;
    var size = file.size;
    var type = file.type;

    if (file.name.length < 1) {
       return false;;
    }
    else if (file.size > 10000000) {
       toastr.error('Error', 'Failed to upload image<span class=\"errorText\"><br/>Selected file is greater than 10MB.</span>');
       return false;;
    }
    else if (file.type != 'image/png' && file.type != 'image/jpg' && !file.type != 'image/gif' && file.type != 'image/jpeg') {
       toastr.error('Error', 'Failed to upload image<span class=\"errorText\"><br/>Selected file must be in one of the following formats: .gif, .jpeg, .jpg, .png.</span>');
       return false;
    }

    var formData = new FormData();
    formData.append("name", name);
    formData.append("size", size);
    formData.append("type", type);
    formData.append("file", file);

    $.ajax({
       type: "POST",
       url: 'Pages.aspx/UploadImage',
       data: formData,
       cache: false,
       contentType: false,
       processData: false,
       success: function (data) {
          data = data.d;
          if (data == -2) {
             toastr.error('Error', 'Failed to upload image<span class=\"errorText\"><br/>You do not have the required permissions to upload images.</span>');
          } else if (data == -3) {
             toastr.error('Error', 'Failed to upload image<span class=\"errorText\"><br/>There was a fatal error. Please contact support.</span>');
          } else {
             toastr.success('Success', 'Image Id <b>' + data + '</b> was saved successfully.');
          }
       },
       error: function (err) {
          toastr.error('Error', 'Failed to upload image<span class=\"errorText\"><br/>There was a fatal error. Please contact support.</span>');
       }
    });
 }

The associated web method is currently blank:

 [WebMethod]
 public static int UploadImage(object Data)
 {
    if (!(Security.checkAccess("/pages/Pages.aspx").Contains("w"))) // 
    {
       return -2;
    }
    else
    {
       return -3;
    }
 }

The web method will eventually save the file and return the ImageId or associated error integer.

Currently, the AJAX call to the web method does not occur, it simply provides a success message when it should only return one of the two error messages.

Is there something glaring that I am missing? Any help will be greatly appreciated.

Upvotes: 1

Views: 11241

Answers (1)

user4102487
user4102487

Reputation:

I think the jquery ajax method may still not support reading files from your computer, which was always the case with javascript because of security until recent updates to the XMLHttpRequest object made it possible.

The solution I see people using to make this work is always to use the low level object instead of jquery or resort to the old iframe tricks (or worse yet, flash!)

this guys has a really nice tutorial about it. see it if it helps you:

http://blog.teamtreehouse.com/uploading-files-ajax

Upvotes: 1

Related Questions