Search code examples
javascriptajaximage-uploadinggeneric-handler

Change filename of picture in generic handler


I have a generic handler that is setup to receive a picture from an ipad running html5 and javascript.

All the code is working front to back, short one thing.

I need to change the filename of the picture once it is handled in the generic handler.

Here is my button click code -

function sendPic() {
  checkNetwork();
  var myInput = document.getElementById('myFileInput');
  var file = myInput.files[0];
  var formData = new FormData();
  formData.append('file', $('#myFileInput')[0].files[0]);
  $.ajax({
    type: 'post',
    url: domainLocation + 'saveimage.ashx',
    data: formData,
    success: function (status) {
      if (status != 'error') {
        var my_path = "MediaUploader/" + status;
        $("#myUploadedImg").attr("src", my_path);
      }
    },
    processData: false,
    contentType: false,
    error: function () {
      alert("Whoops something went wrong!");
    }
  });
}

Here is the generic handler code -

    public void ProcessRequest(HttpContext context)
{
  string fname;

  if (context.Request.Files.Count > 0)
  {
    HttpFileCollection files = context.Request.Files;
    for (int i = 0; i < files.Count; i++)
    {
      HttpPostedFile file = files[i];

      if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE" || HttpContext.Current.Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER")
      {
        string[] testfiles = file.FileName.Split(new char[] { '\\' });
        fname = testfiles[testfiles.Length - 1];
      }
      else
      {
        fname = file.FileName;
      }
      file.SaveAs(@"\\fdsvr\mwfphotos\" + fname);
      context.Response.ContentType = "text/plain";
      context.Response.Write(fname);
    }
  }
}

I was thinking of doing the data block in the ajax call

    data: {
  "fileName" : fileName,
  "formData" : formData
},

This direction seems to fall down at the handler - trying to get the formData and the filename from the context.

Am i going in the right direction? Am i not setting up the data payload correctly in the ajax call? once in the handler, how would i bring the formData out of the context and use it within?

thank you


Solution

  • Although I've used JavaScript together with AJAX and PHP to achieve something similiar, I think this link on the Mozilla Developer Network could help you building your application.

    Here it's suggested to supply a third argument for formData.append like formData.append('userpic', myFileInput.files[0], 'chris.jpg'); in order to supply a specific filename.