This is common problem developer faced during development that how to upload file with complex data. I was one of them. So to solve this I searched a lot and but did not get satisfied answer. Then I combined many of answer and solve my problem. I am sharing my code here.
Very first my web api code is as below:
public HttpResponseMessage UploadData()
{
try
{
//if (HttpContext.Current.Request.Files.AllKeys.Any())
if (HttpContext.Current.Request.Form.AllKeys.Any())
{
var Title = HttpContext.Current.Request.Form["Title"];
var Id = HttpContext.Current.Request.Form["Id"];
var H2 = HttpContext.Current.Request.Form["H2"];
var H3 = HttpContext.Current.Request.Form["H3"];
var P = HttpContext.Current.Request.Form["P"];
var pic = new HttpPostedFileWrapper(HttpContext.Current.Request.Files["Picture"]);
return Request.CreateResponse(HttpStatusCode.OK, "Successfully uploaded");
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Please enter information to submit");
}
}
catch (System.Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message);
}
}
Now HTML form that we are using to take data:
@model Admin.Models.UploadData
<form id="frmData" name="frmData" method="post" enctype="multipart/form-data" >
@Html.TextBoxFor(model => model.ImageUpload, new { type = "file", id = "ImageUpload", name = "ImageUpload", @class = "default" })
@Html.TextBoxFor(model => model.Title, new { id = "Title", name = "Title", @class = "m-wrap span12" })
@Html.TextBoxFor(model => model.H2, new { id = "H2", name = "H2", @class = "m-wrap span12" })
@Html.TextBoxFor(model => model.H3, new { id = "H3", name = "H3", @class = "m-wrap span12" })
@Html.TextBoxFor(model => model.P, new { id = "P", name = "P", @class = "m-wrap span12" })
<span id="spnError" class="field-validation-error"></span>
<button type="submit" id="btnSubmit" class="btn blue"><i class="icon-ok"></i> Save</button>
</form>
Now Its time to call web api from Ajax
$('#btnSubmit').click(function (e) {
e.preventDefault();
if ($('#ImageUpload').val() == "" && $('#Id').val() == "0") {
$('#spnError').text("Please select image");
return false;
}
else {
if ($('#ImageUpload').val() != "") {
var fileExtension = ['jpeg', 'jpg'];
if ($.inArray($('#ImageUpload').val().split('.').pop().toLowerCase(), fileExtension) == -1) {
$('#spnError').text("Only '.jpeg','.jpg' formats are allowed");
return false;
}
else {
var fsize = $('#ImageUpload')[0].files[0].size;
if (fsize > 1048576) //do something if file size more than 1 mb (1048576)
{
$('#spnError').text("Max image size limit is 1 MB");
return false;
}
}
}
}
if ($('#Title').val() == "") {
$('#spnError').text("Please enter Title");
return false;
}
var data = new FormData();
var files = $("#ImageUpload").get(0).files;
if (files.length > 0) {
data.append("Picture", files[0]);
}
data.append("Title", $('#Title').val());
data.append("Id", $('#Id').val());
data.append("H2", $('#H2').val());
data.append("H3", $('#H3').val());
data.append("P", $('#P').val());
$(this).html("<i class='icon-refresh'></i> processing");
$.ajax({
url: "@Url.Action("UploadData", "api/Webapi")",
type: "POST",
processData: false,
contentType: false,
data: data,
success: function (response) {
//code after success
$('#btnSubmit').html("<i class='icon-ok'></i> Save");
alert(response);
},
error: function (response) {
$('#btnSubmit').html("<i class='icon-ok'></i> Save");
if ((JSON.parse(response.responseText).Message).indexOf("login") >= 0) {
window.location = "@Url.Action("Index","Home")";
}
else {
$('#spnError').text(JSON.parse(response.responseText).Message);
}
}
});
});
That’s it … Enjoy coading…
No comments:
Post a Comment