Ajax doesn't work by retrieving big file from database - javascript

By retrieving file more than 0.5MB from SQL database ajax falls into error every time, what am I doing wrong here?
$(document).ready(function () {
loadFileData();
});
function loadFileData() {
$.ajax({
type: "GET",
url: "/File/FileIndex",
dataType: "JSON",
success: function (data) {
$.each(data, function (i, val) {
var trow = $('<tr/>').data("id", val.id);
var trowa = $('<tr/>');
var trowb = $('<tr/>').data("id", val.id);
trow.append('<td colspan="2">' + escape(val.Name) +'</td>');
trowa.append('<td><input type="file" id="FileUpload" /></form></td>');
trowb.append('<td><input type="button" class="btnUpload" value="Upload File" /><input type="button" id="btnClear" value="Clear" /></td>');
tab.append(trow);
tab.append(trowa);
tab.append(trowb);
});
$("#showFiles").html(tab);
},
error: function (error) {
alert("Failed! Please try again." + error);
}
});
var tab = $('<table style="width:100px" border=1 class=MyTable></table>');
}
my controller:
//GET: File
public JsonResult FileIndex()
{
List<tblFile> fileList = new List<tblFile>();
using (FileDBEntities db = new FileDBEntities())
{
fileList = db.tblFiles.ToList();
}
return new JsonResult { Data = fileList, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
with small files it works perfectley, but why it falls down by retriving file more than 0,5MB?
message, what I'm reciving:
function(){if(a){var t=a.length;(function r(t){v.each(t,function(t,n){var i=v.type(n);i==="function"?
(!e.unique||!c.has(n))&&a.push(n):n&&n.length&&i!=="string"&&r(n)})})(arguments),i?o=a.length:n&&(s=t,l(n))}return this}

I think you should:
Your Controller: you should return with binary || file Stream
//GET: File
public JsonResult FileIndex()
{
List<byte> fileList = new List<byte>();
using (FileDBEntities db = new FileDBEntities())
{
fileList = db.tblFiles.ToList();
foreach(var itemFile in fileList) {
fileList.add(File.ReadAllBytes(itemFile));
}
}
return new JsonResult { Data = fileList, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}

Related

How to keep list of image files in a var [] and send them to controller at once

I need to send array of image files to a controller. Below I have sent one file to the controller, but I need to send a list of image files.
My Controller:
public async Task<IActionResult> AddImage(string emailid , List<IFormFile> imagefile)
{
ImageUpload img=new ImageUpload();
var emailId = feedBackContext.UserMasters.FirstOrDefault(m=>m.Email==emailid);
foreach (var item in imagefile)
{
if (item.Length > 0)
{
using (var stream = new MemoryStream())
{
await item.CopyToAsync(stream);
img.imagefile = stream.ToArray();
}
}
}
img.EmailID = emailId.UserMasterID;
var existimage = feedBackContext.ImageUpload.FirstOrDefault(m => m.EmailID == emailId.UserMasterID);
if (existimage == null)
{
feedBackContext.ImageUpload.Add(img);
feedBackContext.SaveChanges();
return RedirectToAction("Index");
}
else
{
feedBackContext.ImageUpload.Remove(existimage);
feedBackContext.SaveChanges();
feedBackContext.ImageUpload.Add(img);
feedBackContext.SaveChanges();
return RedirectToAction("Index");
}
}
My JavaScript file:
(I need to send array of image files to the controller like passing array)
function sendArr(form)
var []=imgarr;
{
$.ajax(
{
type: "POST",
traditional: true,
url: form.action,
data: { dataList: arr, imageList: imgarr },
dataType: "json",
success: function (asd) {
document.getElementById("QuestionDescription").value = "";
document.getElementById("AnswerDescription").value = "";
count = 0;
$('#demo').remove();
document.getElementById("QuestionDescription").focus();
window.location.href = '';
}
});
}
}
My Form::
<script>
function addAnswer() {
imgarr[count] = document.getElementById('imagefile').value;
}
</script>
<form asp-action="AddImage">
<input type="file" id="imagefile" name="imagefile" />
</form>
Help me if you know something regarding this.
Consider your form looks similar to this:
<form action="" method="post" enctype="multipart/form-data">
<label for="file1">Filename:</label>
<input type="file" name="files" id="file1" />
<label for="file2">Filename:</label>
<input type="file" name="files" id="file2" />
<input type="submit" />
</form>
Controller:
You need to use IEnumerable<HttpPostedFileBase>
[HttpPost]
public ActionResult Index(IEnumerable<HttpPostedFileBase> files) {
foreach (var file in files) {
if (file.ContentLength > 0) {
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
file.SaveAs(path);
}
}
return RedirectToAction("Index");
}
The files variable refers to the name attribute in the form fields.
You can also stuff the variable inside a model if you like.
Example taken from here

ASP.NET MVC ADO.NET Query per table row

Here I have this table:
If I click the button, I want to pass the table per row to the controller, then perform ADO.NET Query per row, like for example, perform "UPDATE tbluser SET note='INACTIVE' WHERE id=#id" per row.
One of the main purpose of this is when i filter the table, only the visible rows will be passed.
I already have a code here to pass to controller using AJAX but I don't know what to do afterwards.
JS:
var HTMLtbl =
{
getData: function (table) {
var data = [];
oTable.rows({ search: 'applied' }).every(function () {
var cols = [];
var rowNode = this.node();
$(rowNode).find("td").each(function () {
cols.push($(this).text().trim() || null);
});
data.push(cols);
});
return data;
}
}
$("btnSubmit").on("click", function () {
var data = HTMLtbl.getData($(".datatable"));
var parameters = {};
parameters.array = data;
var request = $.ajax({
async: true,
cache: false,
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/Home/SubmitTable",
data: JSON.stringify(parameters),
success: function () {
window.location.href = "/Home/Index";
}
});
request.fail(function (jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
});
Controller:
[HttpPost]
public JsonResult SubmitTable(string[][] array)
{
//I don't know what to do here now, please help
}
My Solution based on Mostafa's answer:
JS:
var HTMLtbl =
{
getData: function () {
var data = [];
oTable.rows({ search: 'applied' }).every(function () {
var cols = [];
var rowNode = this.node();
$(rowNode).find("td").each(function () {
cols.push($(this).text().trim() || null);
});
data.push(cols);
});
return data;
}
}
$("#btnSubmit").on("click", function () {
var data = HTMLtbl.getData($(".datatable"));
var parameters = {};
parameters.array = data;
var request = $.ajax({
async: true,
cache: false,
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/Home/SubmitTable",
data: JSON.stringify(parameters),
success: function () {
window.location.href = "/Home/Index";
}
});
request.fail(function (jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
});
Controller:
[HttpPost]
public JsonResult SubmitTable(string[][] array)
{
string result = string.Empty;
try
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
con.Open();
foreach (var arr in array)
{
SqlCommand cmd = new SqlCommand("UPDATE tbluser SET remark='INACTIVE' WHERE id = #id", con);
cmd.Parameters.AddWithValue("#id", arr[0]);
cmd.ExecuteNonQuery();
}
con.Close();
}
catch (Exception ex)
{
result = ex.Message;
}
return Json("Records updated successfully.", JsonRequestBehavior.AllowGet);
}
I can now use this for more complicated stuff, thanks
If you want to update a custom row you can add a button for each row with custom text and icon, then add a "data-" attribute to this button and path your row id,
<input type="button" data-rowId="1" class="changeActivationState">activate</input>
in this example I added a data field to my imput after that I define this javascript method:
$(".changeActivationState").click(function(){
$(this).data("rowId")//get the selected row id and call you service
});
using this code you can read first element for each row and perform a web service call for all rows
var arr = [];
$("#yourtable tr").each(function(){
arr.push($(this).find("td:first").text()); //put elements into array
});
and using this code you can read all rows into a json object
var tbl = $('#yourtable tr').map(function() {
return $(this).find('td').map(function() {
return $(this).html();
}).get();
}).get();
assume that you passed the list to action
int[] passedIDsfromBrowser = ///filled with data that comes from browser;
SqlConnection connection = ....
SqlCommand command = new SqlCommand(connection);
command.CommandText = "Update MYTABLENAME Set Active = true where ID in (" string.Join(",", passedIDsfromBrowser ) + ")";
connection.Open();
command.ExecuteNonQuery();
connection.Close();
this is a pseudo code.
or if you want a loop and updating each row with a loop
SqlConnection connection = ....
SqlCommand command = new SqlCommand(connection);
connection.Open();
for(int i = 0 ; i < passedIDsfromBrowser.Length; i++){
command.CommandText = "YOURQUERY";
command.ExecuteNonQuery();
}
connection.Close();

My Request.Files in action side is always null when uploading file by ajax in MVC

I need to upload an image by ajax mode in MVC .I used this method everything is ok in Js code it gets the formdata and the ajax request is sent to the controller correctly but in my controler i get Request.File["myfile"] always null ... i seached everywhere for the solution but didn't find please help me thats so emergency ... Thank's all
here is my js codes :
function UploadImage() {
var data = new FormData();
var files = $("#myfile").get(0).files;
if (files.length > 0) {
data.append("MyImages", files[0]);
}
$.ajax({
url: "#Url.Action("SaveFile","Home")",
type: "POST",
processData: false,
contentType: false,
enctype: 'multipart/form-data',
data: {},
success: function (response) {
//code after success
console.log(response);
alert(response);
},
error: function (er) {
alert(er);
}
});
}
Html:
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>upload</title>
<link href="~/Content/bootstrap.css" rel="stylesheet" />
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
</head>
<body>
<div class="row">
<div class="container">
<div>
file:<input type="file" id="myfile" style="display: block"/>
<br />
<input type="button" value="save" id="btnUpload" onclick="UploadImage()"/>
</div>
</div>
</div>
</body>
</html>
and My Action:
[HttpPost]
public JsonResult SaveFile()
{
var uniqueName = "";
if (Request.Files["myfile"] != null)
{
var file = Request.Files["myfile"];
if (file.FileName != "")
{
var ext = System.IO.Path.GetExtension(file.FileName);
uniqueName = System.Guid.NewGuid().ToString() + ext;
var rootPath = Server.MapPath("~/Upload/");
var fileSavePath = System.IO.Path.Combine(rootPath, uniqueName);
file.SaveAs(fileSavePath);
}
}
return Json(new
{
success=false,
name=uniqueName
},JsonRequestBehavior.AllowGet);
}
Following this example that is very similar to your code
change this
data: {}
by this
data: data
Sample code VIEW
<input type="file" id="FileUpload1" />
<input type="button" id="btnUpload" value="Upload Files" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#btnUpload').click(function () {
// Checking whether FormData is available in browser
if (window.FormData !== undefined) {
var fileUpload = $("#FileUpload1").get(0);
var files = fileUpload.files;
// Create FormData object
var fileData = new FormData();
// Looping over all files and add it to FormData object
for (var i = 0; i < files.length; i++) {
fileData.append(files[i].name, files[i]);
}
// Adding one more key to FormData object
fileData.append('username', ‘Manas’);
$.ajax({
url: '/Home/UploadFiles',
type: "POST",
contentType: false, // Not to set any content header
processData: false, // Not to process data
data: fileData,
success: function (result) {
alert(result);
},
error: function (err) {
alert(err.statusText);
}
});
} else {
alert("FormData is not supported.");
}
});
});
</script>
Sample Code CONTROLLER
[HttpPost]
public ActionResult UploadFiles()
{
// Checking no of files injected in Request object
if (Request.Files.Count > 0)
{
try
{
// Get all files from Request object
HttpFileCollectionBase files = Request.Files;
for (int i = 0; i < files.Count; i++)
{
//string path = AppDomain.CurrentDomain.BaseDirectory + "Uploads/";
//string filename = Path.GetFileName(Request.Files[i].FileName);
HttpPostedFileBase file = files[i];
string fname;
// Checking for Internet Explorer
if (Request.Browser.Browser.ToUpper() == "IE" || Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER")
{
string[] testfiles = file.FileName.Split(new char[] { '\\' });
fname = testfiles[testfiles.Length - 1];
}
else
{
fname = file.FileName;
}
// Get the complete folder path and store the file inside it.
fname = Path.Combine(Server.MapPath("~/Uploads/"), fname);
file.SaveAs(fname);
}
// Returns message that successfully uploaded
return Json("File Uploaded Successfully!");
}
catch (Exception ex)
{
return Json("Error occurred. Error details: " + ex.Message);
}
}
else
{
return Json("No files selected.");
}
}

How to upload image on server side using javascript and html file control in asp.net c#?

I am using javascript method to upload image using ajax call.
It successfully uploaded on localhost machine but on server machine it throws erro of GDI+.
I uploaded image in the folder of the same project and shows those images.
Here is my way,
HTML:
<input type="file" name="file" id="file" class="inputfile" onchange="PreviewImageForLabel(this)" />
<input type="hidden" id="hdnSource1" value="" />
<input type="hidden" id="hdnFileName1" value="" />
Javascript code:
function PreviewImageForLabel(input) {
if (input.files && input.files[0]) {
var filerdr = new FileReader();
filerdr.onload = function (e) {
document.getElementById('hdnSource1').value = e.target.result; //Generated DataURL
document.getElementById('hdnFileName1').value = input.value.substring((input.value.lastIndexOf("\\")) + 1)
document.getElementById('txt_ImageSource1').value = "Images/" + document.getElementById('hdnFileName1').value;
UploadFileForLabel();
}
filerdr.readAsDataURL(input.files[0]);
}
}
function UploadFileForLabel() {
$.ajax({
type: "POST",
url: "frmlblExpression.aspx/UploadFile", //pageName.aspx/MethodName
contentType: "application/json;charset=utf-8",
data: "{'dataURL':'" + document.getElementById('hdnSource1').value + "','fileName':'" + document.getElementById('hdnFileName1').value + "'}", // pass DataURL to code behind
dataType: "json",
success: function (data) {
alert(data.d); // Success function
$("#btnSelectImage").trigger('click');
},
error: function (result) {
alert(result.d); //Error function
}
});
}
C# code:
[WebMethod]
public static string UploadFile(string dataURL, string fileName)
{
string directoryPath = HttpContext.Current.Server.MapPath("~/Bin-debug/Images");
try
{
if (!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
Bitmap varBmp = Base64StringToBitmap(dataURL);
byte[] byteBuffer = Convert.FromBase64String(dataURL.Split(',')[1].ToString());
//Bitmap newBitmap = new Bitmap(varBmp);
//varBmp.Dispose();
//varBmp = null;
//newBitmap.Save(HttpContext.Current.Server.MapPath("//Bin-debug/Images/" + fileName));
using (MemoryStream ms = new MemoryStream(byteBuffer))
{
using (Bitmap bm2 = new Bitmap(ms))
{
bm2.Save(HttpContext.Current.Server.MapPath("//Bin-debug/Images/" + fileName));
}
}
return "File has been uploaded successfully..!!";
}
catch (Exception ex)
{
return ex.Message.ToString();
}
}

how send table content to controller

I have a problem to send table global from view to controller the table in controller is full but in controller affect a null for the composant of table
and this is the controller method :
public Boolean ajoutermodule(string nom, modules[] global, int cv)
{
return true;
}
And this the view and method ajax how i append my table global and how i sent this table global from view to controller :
function Addmodule() {
var nom = $("#nomprojet_I").val();
var cv = global.length;
$.ajax({
url: "/Module/ajoutermodule",
type: "POST",
dataType: 'json',
data: {
"nom": nom,
"global": global,
"cv": cv,
},
success: function (responseText) {
debugger;
if (responseText == "True") {
alert("Succes");
}
else {
alert("error");
}
}
});
}
var global = [];
function OnGetSelectedFieldValues(s, e) {
var SelectedUsers = $("#teamlist_I").val() + " " + $("#teamid_I").val();
listbox.AddItem(SelectedUsers);
var nom = $("#teamlist_I").val();
var id = $("#teamid_I").val();
global.push({ "id": id, "nom": nom });
debugger;
}
and when i added the length it send him correctly to controller.
but method ion your controller like this:
public Boolean ajoutermodule(string nom, stirng s, int cv)
{
return true;
}
and add this to your method ajax
var s = JSON.stringify(global);
function Addmodule() {
var nom = $("#nomprojet_I").val();
var s = JSON.stringify(global);
var cv = global.length;
$.ajax({
url: "/Module/ajoutermodule",
type: "POST",
dataType: 'json',
data: {
"nom": nom,
"s": s,
"cv": cv,
},
success: function (responseText) {
debugger;
if (responseText == "True") {
alert("Succes");
}
else {
alert("error");
}
}
});
}
it will work inchallah
Please try this code for ASP.NET MVC –
View.cshtml
<table id="StepsTable">
<tr>
<td>Step 1</td>
<td>#Html.TextBox("step1")</td>
</tr>
<tr>
<td>Step 2</td>
<td>#Html.TextBox("step2")</td>
</tr>
<tr>
<td>Step 3</td>
<td>#Html.TextBox("step3")</td>
</tr>
</table>
<input id="SendToControllerButton" type="button" value="Send to the server"/>
<script>
$(document).ready(function () {
$("#SendToControllerButton").click(function () {
var data = {};
//Collects the data from textboxes and adds it to the dictionary
$("#StepsTable tr").each(function (index, item) {
var tds = $(this).find("td");
var textBoxTitle = $(tds).eq(0).text();
var textboxValue = $(tds).eq(1).find("input").val();
data["stepsDictionary[" + index + "].Key"] = textBoxTitle;
data["stepsDictionary[" + index + "].Value"] = textboxValue;
});
//Makes ajax call to controller
$.ajax({
type: "POST",
data: data,
url: "/Home/ProcessStepsValues",
success: function (message) {
alert(message);
}
});
});
});
</script>
And then sends the data to controller
Controller.cs
[HttpPost]
public string ProcessStepsValues(Dictionary<string, string> stepsDictionary)
{
string resultMessage = string.Empty;
if (stepsDictionary != null)
{
resultMessage = "Dictionary data passes to controller successfully!";
}
else
{
resultMessage = "Something goes wrong, dictionary is NULL!";
}
return resultMessage;
}
Please refer the site for more details
https://alexkuznetsov.wordpress.com/2013/05/08/asp-net-mvc-pass-dictionary-data-from-view-to-controller/

Categories

Resources