Unable to receive object FormData from JQuery Ajax in WebApi method: HttpContext.Current.Request.Files[0] returns null - form-data

I have tried many suggestions from stack overflow earlier threads, but the issue still do not seem to be resolving.
Client Side Code:
var file = document.getElementById('MainForm_main_panel_company_code_change_file').files[0];
var formData = new FormData();
formData.append("file", file);
data = '[0, {"data":{"args":"'+formData+'"}}]';
$.ajax({
url: 'Control/MainForm.main_panel.company_code_change/GetData',
type: 'POST',
data: data,
contentType: false,
processData: false,
dataType: 'json',
success: function (result) {
if (result.msg === undefined) {
JSMessage.show("Success", "Report Generated Successfully");
} else
JSMessage.show("Error", "Report Generation Failed:" +result.msg.text);
}
Note: If I don't mention data = '[0, {"data":{"args":"......., it throws error: 'data is required'
Server Side Code:
public class CompanyCodeChangeArg
{
public string args;
public CompanyCodeChangeArg()
{
F<IMNull<CompanyCodeChangeArg>>.Instance.SetNull(this);
}
}
[HttpPost]public string GetData(CompanyCodeChangeArg arg)
{
var file = System.Web.HttpContext.Current.Request.Files[0];
HttpPostedFileBase filebase = new HttpPostedFileWrapper(file);
var fileName = Path.GetFileName(filebase.FileName);
var path = Path.Combine(System.Web.Hosting.HostingEnvironment.MapPath("~/App_Data/Uploads/"), fileName);
filebase.SaveAs(path);
return "";
}
Please help me here, I need to upload the file using WebApi Method and JQuery AJAX,
Tried various suggestions on stack overflow but it did not worked

Related

Why my controller not getting data from ajax

I'm new to this, I'm trying to get the data from an ajax query
This Is My Ajax
$('#insertfile').on('click',function() {
console.log('a');
var file = document.getElementById('files').files[0];
var name = document.getElementById('names').value;
if( $('#room-status-no').prop('checked') ) {
console.log("status: 1");
var status = 1;
} else {
var status = 0;
console.log("status: 0");
}
var id = document.getElementById('id').value;
let form = new FormData();
console.log(file);
form.append('file', file);
form.append('name', name);
form.append('status', status);
form.append('id', id);
form.append('_method', 'PATCH');
form.append('action', 'update_file');
console.log(id, name, status);
$.ajax({
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
url: "{{ route('this is my route.update', 'update_file') }}",
type: "PATCH",
cache: false,
processData: false,
contentType : false,
dataType: 'json',
data: form,
beforeSend: function() {
$('body').append('<div id="spinnerLoading"><div class="sk-spinner sk-spinner-double-bounce"><div class="sk-double-bounce1"></div><div class="sk-double-bounce2"></div></div></div>');
},
This is my Controller
public function update(Request $request) {
$action = $request->action;
dd($request->all());
if($action == 'update_text'){
return $this->updatetextControl($request);
} else if($action == 'update_file') {
return $this->updateFileControl($request);
}
I'm trying to pass the form data to my laravel controller using dd($request->all());
I was unable to get any data in my controller, I'm not sure if my URL route is the problem or I cant have multiple update functions others thing in one controller, does anyone know a solution? it will be much appreciated, thanks

How submit captcha to the controller using ajax and form data

I have a form with some fields and file upload, rendering as a partial view using ajax in asp.net MVC. when submitting the form, I want to pass all the data to the controller. But if I use $("form").serialize(), it is not passing the selected file to the controller. So I am using formData() to pass the data to the controller. Till this point, everything works fine.
But after adding captcha using CaptchaMvc, it not reaching the controller. Even if I enter valid captcha, it is invalid in the controller.
This is how I send data to the controller using the ajax and formData
var data = new FormData();
var vidFile = null;
if ($("#FileUpload")[0].files.length > 0)
vidFile = $("#FileUpload")[0].files[0];
data.append("detail", $("#detail").val());
data.append("name", $("#name").val());
data.append("FileUpload", vidFile);
$.ajax({
url: "/home/submitData",
type: "POST",
contentType: false,
processData:false,
data: data,
success: function (response) {
if (response.success == true) {
} else {
}
}
});
Is there any way to pass the captcha as well to the controller?
Why can't you validate using different controller function, as follows:
At the time of submission, validate the captcha first, and depending on the result, call another controller function to submit data or show the error.
var submitData = function(){
var data = new FormData();
var vidFile = null;
if ($("#FileUpload")[0].files.length > 0)
vidFile = $("#FileUpload")[0].files[0];
data.append("detail", $("#detail").val());
data.append("name", $("#name").val());
data.append("FileUpload", vidFile);
$.ajax({
url: "/home/submitData",
type: "POST",
contentType: false,
processData:false,
data: data,
success: function (response) {
if (response.success == true) {
//Success
} else {
//Submission failed
}
}
});
}
var validateCaptcha = function(){
$.ajax({
url: "/home/validateCaptcha",
type: "POST",
data: $("form").serialize(),
success: function (response) {
if (response.success == true) {
submitData();
} else {
alert("Invalid Captcha entry");
}
}
});
}
$("form").submit(function(e){
validateCaptcha();
});

Passing more then 1 value to webmethod using FormData via Ajax

I'm trying to pass the uploaded image + two additional parameters to my web service using the FormData method from my Ajax method as shown here:
var formData = new FormData();
formData.append('file', $('#photo')[0].files[0]);
formData.append('u', "test");
formData.append('s', "Testing");
My ajax call is outlined like so:
$.ajax({
url: "/admin/WebService/test.asmx/UploadImage",
type: "POST",
processData: false,
contentType: false,
data: formData,
success: function (response) {
console.log(response);
},
error: function (er) {
alert(er);
}
});
Which calls this webmethod:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string UploadImage()
{
if (System.Web.HttpContext.Current.Request.Files.AllKeys.Any())
{
var t= System.Web.HttpContext.Current.Request.Files["s"];
var c= System.Web.HttpContext.Current.Request.Files["u"];
var p = System.Web.HttpContext.Current.Request.Files["file"];
}
else
{
return "Error";
}
return "Error";
}
The issue I'm having is the parameters 'u' and 's' are null yet when referencing file I'm able to get its value.
Whilst searching the web I was under the impression you can specify as many key/values are required when using this approach unless I have been misinformed? can someone please shed some light into why these two parameters are null? Thanks in advance.
This works for me:
JavaScript
var formData = new FormData();
formData.append("UserId", userId);
formData.append("RequestPhoto", imageFile);
formData.append("RequestVoiceRecord", voiceFile);
formData.append("Latitude", latitude);
formData.append("Longitude", longtitude);
$.ajax({
type: "POST",
url: "/User/CreateRequest",
data: formData,
contentType: false,
processData: false,
success: function () {
alert("OK");
},
error: function () {
alert("Error");
}
});
Controller:
public class UserController : ApiController
{
[HttpPost]
public int CreateRequest()
{
// HttpResponseMessage result = null;
var httpRequest = HttpContext.Current.Request;
var req = new UserRequest
{
UserId = Guid.Parse(httpRequest.Form["UserId"]),
Photo = httpRequest.Files["RequestPhoto"],
VoiceRecord = httpRequest.Files["RequestVoiceRecord"]
Latitude = float.Parse(httpRequest.Form["Latitude"]),
Longitude = float.Parse(httpRequest.Form["Longitude"]),
};
You should create one json instead of create this stuff, add whatever keys you want to sent via ajax.
var formData = {'u':'value','s':'value'}
$.ajax({
url: "/admin/WebService/test.asmx/UploadImage",
type: "POST",
processData: false,
contentType: false,
data: JDON.Stringify(formData),
success: function (response) {
console.log(response);
},
error: function (er) {
alert(er);
}
});
try using this way.

Posting Image Data From Ajax to WebAPI

I am trying to pass a image dat to a web API method using example code I found on here http://www.asp.net/web-api/overview/working-with-http/sending-html-form-data,-part-2 and I am finding that MultipartFormDataStreamProvider.FileData is always empty. Why might this be? Also, is this the right approach to be taking? Are there options? I am trying to pass only a single image.
The Call
var t = new FormData();
t.append('file-', file.id);
t.append('filename', file.name);
t.append('Size', file.size);
$.ajax({
url: sf.getServiceRoot('mySite') + "upload/PostFormData",
type: "POST",
data: t,
contentType: false,
processData: false,
beforeSend: sf.setModuleHeaders
}).done(function (response, status) {
alert(response);
}).fail(function (xhr, result, status) {
alert("error: " + result);
});
});
public async Task<HttpResponseMessage> PostFormData()
{
// Check if the request contains multipart/form-data.
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
string root = HttpContext.Current.Server.MapPath("~/App_Data");
var provider = new MultipartFormDataStreamProvider(root);
try
{
// Read the form data.
await Request.Content.ReadAsMultipartAsync(provider);
// This illustrates how to get the file names.
foreach (MultipartFileData file in provider.FileData)
{
Trace.WriteLine(file.Headers.ContentDisposition.FileName);
Trace.WriteLine("Server file path: " + file.LocalFileName);
}
return Request.CreateResponse(HttpStatusCode.OK);
}
catch (System.Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
}
I could get fileData properly when posted via form,
as in sample goes # WebAPI upload error. Expected end of MIME multipart stream. MIME multipart message is not complete
Good Luck,

Send JSON string to a C# method

In my ASP.NET page I have the following method:
public static void UpdatePage(string accessCode, string newURL)
{
HttpContext.Current.Cache[accessCode] = newURL;
}
It actually should receive the accessCode and newURL and update the Cache accordingly. I want to pass the values to that method from JavaScript, using an AJAX request. The code for it is as follows:
function sendUpdate() {
var code = jsGetQueryString("code");
var url = $("#url_field").val();
var dataToSend = [ {accessCode: code, newURL: url} ];
var options = { error: function(msg) { alert(msg.d); },
type: "POST", url: "lite_host.aspx/UpdatePage",
data: {"items":dataToSend},
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function(response) { var results = response.d; } };
$.ajax(options);
}
However this doesn't seem to work. Could anybody help me figure out where the bug is?
UpdatePage is a void method that doesn't return anything, so there is nothing to look at in the response.
You could look at the HTTP return code and check that it was 200 OK or you could modify the web method:
public static bool UpdatePage(string accessCode, string newURL)
{
bool result = true;
try {
HttpContext.Current.Cache[accessCode] = newURL;
}
catch {
result = false;
}
return result
}
Edit:
It looks like your JSON arguments to the WebMethod are incorrect, you don't need the "items" in your JSON. The arguments should match your webmethod exactly.
function sendUpdate() {
var code = jsGetQueryString("code");
var url = $("#url_field").val();
var options = { error: function(msg) { alert(msg.d); },
type: "POST", url: "lite_host.aspx/UpdatePage",
data: {'accessCode': code, 'newURL': url},
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function(response) { var results = response.d; } };
$.ajax(options);
}

Resources