Upload files using JQuery in mobile in Asp.Net mvc

Using jquery methods ajax post and xhr, upload file to server from mobile devices.

 JQuery   
 

Posted: October 26, 2017. | By: mustafa

While developing a small mobile web application I had a need to upload file using JQuery. Let us see basic simple steps to upload the file using jQuery ajax method.



We have set the visibility of a input file as hidden and add javascript to open file dialogue box on click of camera icon. We have set the accept attribute for the input file tag to enable user to pick an existing file, or even use camera to take a shot, and read some attributes of an image using javascript while uploading image.

<form enctype="multipart/form-data" data-ajax="false">

<div class="camera">
 <a href="#" class="camerabutton">
 <img src="/Images/cameraicon.png" onclick="document.getElementById('fileUpload').click(); return false;" />
 </a>
 <input type="file" id="fileUpload" accept="image/*;capture=camera" style="visibility: hidden;" />
 </div>
</form>

//add reference to jQuery in your html.

<script src="~/Scripts/jquery-1.8.2.min.js"></script>

Method to upload file using jquery ajax post method using mobile

While simply adding script for the jquery ajax method

<script>
 $(document).ready(function () {
 $("#fileUpload").change(function () {
 
 var data = new FormData();
 var files = $("#fileUpload").get(0).files;
 // Add the uploaded image content to the form data collection
 if (files.length > 0) {
 data.append("UploadedImage", files[0]);
 //$("#loaderImage").show();
 $("#fileUpload").val('');
 }


 $.ajax({
 type: "POST",
 url: '/TestUpload/UploadFile',
 contentType: false,
 processData: false,
 data: data,
 error: function (xhr, status, error) {
 alert(error);
 },
 success: function (response) {
 
 if (response.Valid) {
 alert(response.ErrorMessage);
 }
 }
 });
 });


});
</script>



In the above example we have done is to upload an image using jquery in mobile it is important to make ajax navigation off by using data-ajax="false" as you cannot upload files using ajax.
Another point is to specify encoding type as enctype="multipart/form-data" on your form definition.


Another method of uploading file using XHR post request using mobile

Here we will use XMLHttpRequest to send data file to the controller to be saved to our server.

Usage -

ajaxMobileUpload('/Features/UploadFile', data, function (response) { alert(response.ErrorMessage); })
function ajaxMobileUpload(apiName, data, callback) {
 //console.log(data);
 //Creating an XMLHttpRequest and sending
 var xhr = new XMLHttpRequest();
 xhr.open('POST', apiName);
 xhr.send(data);
 xhr.onreadystatechange = function () {
 if (xhr.readyState == 4 && xhr.status == 200) {
 if (xhr) {
 if (callback) {
 callback(xhr.responseText);
 }
 }
 }
 }
 }
 



Finally add a method in mvc controller to capture the http file posted while saving it on our server and returning a success message.

[HttpPost]
 public JsonResult UploadFile()
 {
 if (System.Web.HttpContext.Current.Request.Files.AllKeys.Any())
 {
 // Get the uploaded image from the Files collection
 var httpPostedFile = System.Web.HttpContext.Current.Request.Files["UploadedImage"];

if (httpPostedFile != null)
 {
 //imgCompress.Save(httpPostedFile.FileName, fileSavePath);
 }

return Json(new
 {
 Valid = true,
 ErrorMessage = "Upload successfully"
 });
 }
 else
 return Json(new
 {
 Valid = false,
 ErrorMessage = ""
 });
 }

 


related posts

Back to top