How to pass uploaded image path to controller via ajax [duplicate] - javascript

This question already has answers here:
How to append whole set of model to formdata and obtain it in MVC
(4 answers)
Closed 6 years ago.
When passing uploaded file through ajax to asp.net MVC controller, file property is showing null value in controller.
image file object taken by document.getElementById('fileUpload').files[0] action and convert to JSON.stringify(fileName) but when pass that object to asp.net mvc controller
it is showing null value in mvc controller.
please if any one know how to pass that file to ajax to mvc controller, please post your answer
Admin controller
[HttpPost]
public string AddRetailer(HttpPostedFileBase file, string storeName, string storeUrl, string ecommercePlatform)
{
try {
Bswayed.Admin.Retailer retailer = new Bswayed.Admin.Retailer();
return JsonConvert.SerializeObject(data);
} catch (Exception ex) {
throw ex;
}
}
Asp.net upload form
<input type="file" id="fileUpload" name="fileUpload" onchange="this.parentNode.nextSibling.value = this.value"/>Browse
<input class="input-lg"
#Html.TextBoxFor(Model => Model.StoreLogo, new { placeholder=#ViewBag.StoreLogo})
Java script(Ajax)
function AddRetailer()
{
try {
var storeName = $("#StoreName").val();
var storeUrl = $("#StoreURL").val();
var retailerLogoPath = $("#StoreLogo").val();
var ecommercePlatform = $("#EcommercePlatform").val();
var fileName = document.getElementById('fileUpload').files[0]
$.ajax({
url: $("#addRetailer").val(),
cache: false,
type: "POST",
data: {
file:JSON.stringify(fileName),
storeName: storeName,
storeUrl: storeUrl,
ecommercePlatform: ecommercePlatform
},
dataType: "json",
success: function (data) {
},
error: function (resp) {
alert(resp);
}
});
}
catch (e) {
}
}

You don't need to stringfy uploaded image path. Below code is working in my application. I just used FormData() to get all form. After that added all items in form that i want to send to controller. In this case, you don't need to pass parameter in controller. You can get by Request.Files for image & Request.Form for extra data. I hope, It may helps you. If there is any wrong, then share with me, i will sort it out.
Java Script -
function AddRetailer()
{
try {
var storeName = $("#StoreName").val();
var storeUrl = $("#StoreURL").val();
var retailerLogoPath = $("#StoreLogo").val();
var ecommercePlatform = $("#EcommercePlatform").val();
var fileName = document.getElementById('fileUpload')..get(0).files;
var data = new FormData();
if (fileName.length > 0) {
data.append("userUploadedImage", fileName[0]);
data.append("storeName", storeName);
data.append("storeUrl", storeUrl);
data.append("ecommercePlatform", ecommercePlatform);
}
$.ajax({
url: $("#addRetailer").val(),
processData: false,
contentType: false,
type: "POST",
data: data,
success: function (data) {
},
error: function (resp) {
alert(resp);
}
});
}
catch (e) {
}}
Controller -
[HttpPost]
public string AddRetailer()
{
HttpPostedFileBase image = Request.Files["userUploadedImage"];
string storeName = Request.Form["storeName"];
string storeUrl = Request.Form["storeUrl"];
string ecommercePlatform = Request.Form["ecommercePlatform"];
}

Related

how to append model object to formData in AJAX and retrieve using asp.net

I developed an Ajax POST method to pass the data to the controller. First I append my uploaded file to formData. Then I want to bind a model object to it. I did it. But in the controller, my model is always null.
Please help me how to append correctly and get the model and file correctly
javascript function:
var $file = document.getElementById('file'),
$formData = new FormData();
if ($file.files.length > 0) {
for (var i = 0; i < $file.files.length; i++) {
$formData.append('file-' + i, $file.files[i]);
}
}
var SnapShotReceivedData = [{
REASON: REASON_EXEMPT,
COMMENT: COMMENT_EXEMPT,
ATTACHMENT: $formData
}];
SnapShotReceivedData = JSON.stringify({ 'SnapShotReceivedData': SnapShotReceivedData})
$formData.append('SnapShotReceivedData',SnapShotReceivedData);
$.ajax({
contentType: false;
processData: false,
type: 'POST',
url: '#Url.Action("SetHCMNIDSnapData", "Home")',
data: $formData ,
success: function (result) {
},
failure: function (response) {
// $('#result').html(response);
}
});
Controller:
public JsonResult SetHCMNIDSnapData(List<SnapShot> SnapShotReceivedData)
{
if (Request.Files.Count > 0)
{
foreach (string file in Request.Files)
{
var _file = Request.Files[file];
}
}
}
my model is SnapShotReceivedData.When I debug the controller, the model object always null. please help me to solve this.

Download XML received from controller

I need to download an XML received from a controller, but I need the prompt to write a the name and the location where the file will be saved.
First question: is optimal to send the xml like I did in this code or I should send it like a file in some way.
Second question: receiving the xml or the xml file, how can open the prompt and finally save the xml like a file?
[HttpPost]
public ActionResult ExportFiles(string clientName, string currenthcsystem)
{
try
{
var systemActionsConfigurationData = service.GetHcSystemActionsConfigurationData(clientName,currenthcsystem);
XmlSerializer xsSubmit = new XmlSerializer(typeof(HcSystemActionsConfigurationData));
var xml = "";
using (var sww = new StringWriter())
{
using (XmlWriter writer = XmlWriter.Create(sww))
{
xsSubmit.Serialize(writer, systemActionsConfigurationData);
xml = sww.ToString();
}
}
return Content(xml, "text/xml");
}
catch (Exception)
{
throw;
}
}
$('#exportButton').on("click", function () {
var clientName = $(actionsButtons).data('clientname');
var currentHCSystem = $(actionsButtons).data('hcsystemname');
// Create FormData object
var parameters = new FormData();
parameters.append("clientName", clientName);
parameters.append("currentHCSystem", currentHCSystem);
$.ajax({
url: $(actionsButtons).data('export'),
type: 'POST',
data: parameters,
cache: false,
processData: false,
contentType: false,
success: function (response) {
//logic to open the prompt and finally download the xml
},
error: function (err) {
}
});
});

Passing A Single Objects Into An MVC Controller Method Using jQuery Ajax

I'm trying to post a single object data to an MVC Controler using JQuery, Below are my codes.
//declare of type Object of GroupData
var GroupData = {};
//pass each data into the object
GroupData.groupName = $('#groupName').val();
GroupData.narration = $('#narration').val();
GroupData.investmentCode = $('#investmentCode').val();
GroupData.isNew = isNewItem;
//send to server
$.ajax({
url: "/Admin/SaveContributionInvestGroup",
type: "POST",
contentType: "application/json;charset=utf-8",
dataType: "json",
data: JSON.stringify({ GroupData: JSON.stringify(GroupData) }),
success: function (res) {
alertSuccess("Success", res.Message);
//hide modal
$('#product-options').modal('hide');
hide_waiting();
},
error: function (res) {
alertError("Error", res.Message);
}
});
Below is my controller.
[HttpPost]
public JsonResult SaveContributionInvestGroup(ContributionInvestmentGroup GroupData)
{
ClsResponse response = new ClsResponse();
ClsContributionInvestmentGroup clsClsContributionInvestmentGroup = new ClsContributionInvestmentGroup();
var userID = (int)Session["userID"];
var sessionID = (Session["sessionID"]).ToString();
if (contributionGroupData != null)
{
//get the data from the cient that was passed
ContributionInvestmentGroup objData = new ContributionInvestmentGroup()
{
contributionInvestmentGroupID = 0,
groupName = GroupData.groupName,
narration = GroupData.narration,
investmentCode = GroupData.investmentCode,
isNew = GroupData.isNew
};
response = clsClsContributionInvestmentGroup.initiateNewContributionInvestmentGroup(sessionID, objData);
}
else
{
response.IsException = true;
response.IsSucess = false;
response.Message = "A system exception occurred kindly contact your Administrator.";
}
return Json(new
{
response.IsSucess,
response.Message
});
}
The issue is, the data is not been posted to the controller, the controller receives a null object.
Kindly assist, would really appreciate your effort, thanks.
Try Like this:
//send to server
$.ajax({
type: "POST",
url: "/Admin/SaveContributionInvestGroup",
dataType: "json",
data: GroupData,
success: function (res) {
alertSuccess("Success", res.Message);
//hide modal
$('#product-options').modal('hide');
hide_waiting();
},
error: function (res) {
alertError("Error", res.Message);
}
});
in your controller your dont have custom binding to bind JSON to your model thats why you get null in you parameter.
instead just post it as query, try simply changes your ajax option like so:
{
...
contentType: "application/x-www-form-urlencoded", //default:
...,
data: $.param(GroupData),
...
}
and perhaps property names are case sensitive so you will need to change your javascript model's name

Access file using MVC 6 .NET Core with ajax

I am calling this function to send a file via post:
function AddFileHandler() {
return $.ajax({
processData: false,
contentType: false,
type: "POST",
url: '#Url.Action("AddFile", "SomeController")',
data: getFile()
})
}
In my controller, there is this method which produces an error on the first line:
[HttpPost]
public string AddFile()
{
var attachedFile = Request.Form.Files["CsvDoc"]; // there is an error of wrong contentType
return "";
}
My getFile method optains data like this:
function getFile() {
var input = document.getElementById("csvFile");
if (!input || !input.files || !input.files[0]) {
return ";";
}
console.log(input.files[0]); //inputs my file correctly
var data = new FormData();
data.append("CsvDoc", input.files[0]);
}
What exactly am I doing wrong? Does it matter what is in the html?
You're forgetting to return anything from getFile()
simply add
return data;

Get pdf of current page MVC 5

I am trying to get a pdf of a div in my view.
I am doing the following:
I get the element, uri encode its html, then pass it to a method via ajax:
AJAX:
function getPDF(html) {
$.ajax({
type: "POST",
url: "#Url.Action("printPage")",
data: { html: encodeURIComponent(html) }
}).done(function (result) {
window.open("data:application/pdf; " + result);
$("#printArea").html(result);
}).fail(function (data) {
alert("Failed");
});
}
Method:
[HttpPost]
public void printPage(string html)
{
String decoded = System.Uri.UnescapeDataString(html);
var cd = new System.Net.Mime.ContentDisposition
{
FileName = "something.pdf",
Inline = false
};
Response.AppendHeader("Content-Disposition", cd.ToString());
var mem = Bcs.Common.Utilities.HTMLtoPDF.getPDF(decoded);
//var base64EncodedPDF = System.Convert.ToBase64String(pdfByteArray);
Response.BinaryWrite(mem.ToArray());
//return File(mem, System.Net.Mime.MediaTypeNames.Application.Octet);
}
In the end I get a popup to open a pdf but it won't open, according to adobe acrobat it is corrupt.
I tried sending the html as a perameter to the method, but the perameter is too long
HTTP Error 404.15 - Not Found The request filtering module is configured to deny a request where the query string is too long.
What would be a good way of doing this.
public JsonResult printPage(String html)
{
String decoded = System.Uri.UnescapeDataString(html);
var cd = new System.Net.Mime.ContentDisposition
{
FileName = "something.pdf",
Inline = false
};
var mem = Bcs.Common.Utilities.HTMLtoPDF.getPDF(decoded);
mem.Flush();
mem.Position = 0;
String b64Converted = Convert.ToBase64String(mem.ToArray());
return Json(b64Converted, JsonRequestBehavior.AllowGet );
System.Net.Mime.MediaTypeNames.Application.Octet);
}
Then in the view:
$.ajax({
type: "POST",
url: "#Url.Action("printPage")",
data: { html: encodeURIComponent(html) },
}).done(function (result) {
$("#printArea").append('PDF');
}).fail(function (data) {
alert("Failed");
});
Apparently its very easy
Just base64 the pdf and send it over at the json response.

Categories