Is it possible Single Controller for Entire MVC Application to Route Views Or can we Rename Controller Name at Run-time to Route Views?..
i tried below code for route Views working fine.
controller:-
public class HomeController : Controller
{
public ActionResult Commmon_Method(string VN, string Id)
{
return View(#"~/" + VN + ".cshtml");
}
}
view page:
$('#btn_Test').click(function () {
window.location.href = '#Url.Action("Commmon_Method", "Home")?Id=' + 1 + '&VN=' + 'Views/Test/Index2';
});
output URL:-
http://localhost:52296/Home/Commmon_Method?Id=1&VN=Views/Test2/Index
-----------------------------*---------------------
even though i tried myself like MVC based Dynamic Route but not able to succeeded:
http://localhost:52296/Home/Test2/Index
so Controller Name should be single to supply all the request as well as i tried run-time Controller also and custom based Controller not succeed
one more thing i succeed single dynamic JSON Data method in MVC,so no need to write bundle of code to get JSON Data using Jquery Ajax method.
only thing in MVC, Single Controller based Routing Succeeded means MVC will be very Easy Development Apps, So can you Share your knowledge to Simplify the Complex Way of Development
html :-
window.location.href = '#Url.Action("common_dll", "Home")?ctrl=Test';
Controller method to create Controller:
public ActionResult common_dll(string ctrl)
{
StringBuilder sb = new StringBuilder();
sb.Append("using System;" + Environment.NewLine);
sb.Append("using System.Collections.Generic;" + Environment.NewLine);
sb.Append("using System.Data;" + Environment.NewLine);
sb.Append("using System.Data.SqlClient;" + Environment.NewLine);
sb.Append("using System.Dynamic;" + Environment.NewLine);
sb.Append("using System.Linq;" + Environment.NewLine);
sb.Append("using System.Text;" + Environment.NewLine);
sb.Append("using System.Web.Mvc;" + Environment.NewLine);
sb.Append("namespace Testing_MVC.Controllers" + Environment.NewLine);
sb.Append("{" + Environment.NewLine);
sb.Append("public class " + ctrl + "Controller" + " : Controller" + Environment.NewLine);
sb.Append("{" + Environment.NewLine);
sb.Append("public ActionResult Index()" + Environment.NewLine);
sb.Append("{" + Environment.NewLine);
sb.Append("return View();" + Environment.NewLine);
sb.Append("}" + Environment.NewLine);
sb.Append("}" + Environment.NewLine);
sb.Append("}" + Environment.NewLine);
var dir = Server.MapPath("~\\Controllers");
var file = System.IO.Path.Combine(dir, ctrl + "Controller" + ".cs");
System.IO.Directory.CreateDirectory(dir);
System.IO.File.WriteAllText(file, sb.ToString());
return this.RedirectToAction("Index", ctrl, new { id = 1 });
}
public static string JS_NAS(DataSet dss)
{
string str = Newtonsoft.Json.JsonConvert.SerializeObject(dss, Newtonsoft.Json.Formatting.Indented);
return str;
}
public static SqlParameter[] NAS_SQLPRM(string paramstr)
{
#region
string[] parameters = paramstr.Split('~');
string err = string.Empty;
int len = parameters.Length;
SqlParameter[] sqlParam = new SqlParameter[len];
for (int i = 0; i < len; i++)
{
string[] paramWithValue = parameters[i].Split('$');
string param = paramWithValue[0].ToString();
string value = paramWithValue[1].ToString();
sqlParam[i] = new SqlParameter { ParameterName = param, Value = value };
}
return sqlParam;
#endregion
}
[WebMethod]
public static String Insertupdates(string paramstr, string procname)
{
string err = "", dbstr = "";
string[] parameters = paramstr.Split('~');
int len = parameters.Length;
SqlParameter[] sqlParam = new SqlParameter[len];
for (int i = 0; i < len; i++)
{
string[] paramWithValue = parameters[i].Split('$');
string param = paramWithValue[0].ToString();
string value = paramWithValue[1].ToString();
sqlParam[i] = new SqlParameter { ParameterName = param, Value = value };
}
string str = new clsiCMSBLBase().insertData(ref err, ref dbstr, sqlParam, procname);
return err.Replace("$", "") + "$" + dbstr.Replace("$", "");
}
[WebMethod]
public static String GetRowData_Tables(string procedureName, string paramstr)
{
string[] parameters = paramstr.Split('~');
string err = string.Empty;
int len = parameters.Length;
SqlParameter[] sqlParam = new SqlParameter[len];
for (int i = 0; i < len; i++)
{
string[] paramWithValue = parameters[i].Split('$');
string param = paramWithValue[0].ToString();
string value = paramWithValue[1].ToString();
sqlParam[i] = new SqlParameter { ParameterName = param, Value = value };
}
try
{
DataSet ds = new clsiCMSBLBase().GetListData(ref err, sqlParam, procedureName);
String JSONString = String.Empty;
JSONString = Newtonsoft.Json.JsonConvert.SerializeObject(ds, Newtonsoft.Json.Formatting.Indented);
return JSONString;
}
catch (Exception)
{
return "Error";
}
}
var data = getRowData_TableBased('DBSP_ListSupplierGroup', paramstr);
function create_Listgrid(data) {
var cellsrenderer = function (row, column, value) {
return '<div style="text-align: right; margin-top: 5px;">' + (1 + row) + '</div>';
}
$("#jqxgrid").jqxGrid(
{
width: '98%',
height: '370px',
source: { datatype: "json", datafields: [], localdata: data },
filterable: true,
sortable: true,
theme: 'energyblue',
pageable: true,
columnsresize: true,
pagesizeoptions: ['5', '10', '15', '20', '100'],
pagesize: 15,
pagermode: 'default',
enabletooltips: true,
columns: get_cols(data)
/*
columns: [
{ text: 'S.No', dataField: 'Slno', align: 'left', width: '40px', cellsrenderer: cellsrenderer },
{ text: 'MapID', dataField: 'MapID', align: 'left', hidden: true },
{ text: 'PriSupplierID', dataField: 'PriSupplierID', align: 'left', hidden: true },
{ text: "Primary Supp Code", datafield: "PriSuppCode", cellsalign: 'left', align: 'left', width: '140px' },
{ text: "Primary Supplier Name", datafield: "PriSupName", cellsalign: 'left', align: 'left', width: '420px' },
{ text: "Primary Supplier Type", datafield: "PriSupType", cellsalign: 'left', align: 'left', width: '125px', hidden: true },
{ text: 'SecSupplierID', dataField: 'SecSupplierID', align: 'left', hidden: true },
{ text: "Secondary Supplier Code", datafield: "SecSuppCode", cellsalign: 'left', align: 'left', width: '190px' },
{ text: "Secondary Supplier Name", datafield: "SecSupName", cellsalign: 'left', align: 'left', width: '420px' },
{ text: "SecSupType", datafield: "SecSupType", cellsalign: 'left', align: 'left', hidden: true }
]
*/
});
}
function get_cols(data) {
var datacols = new Array();
if (!isEmpty(data) && data.Table1.length > 0) {
$.each(data.Table1, function (name, v) {
if (v.ColumnWidth == 0)
datacols.push({ text: v.ColumnHeader, datafield: v.DataField, hidden: true });
else
datacols.push({ text: v.ColumnHeader, datafield: v.DataField, cellsalign: 'left', align: 'left', width: v.ColumnWidth });
});
$("#<%=btnExport.ClientID%>").show();
}
return datacols;
}
function getRowData_TableBased(procName, paramstr) {
var rowData;
$.ajax({
url: 'Supplier_Group.aspx/GetRowData_Tables',
type: "POST",
dataType: "json",
async: false,
data: "{procedureName: '" + procName + "',paramstr: '" + paramstr + "'}",
contentType: "application/json; charset=utf-8",
success: function (data) {
var response = data.d;
if (response != "Error") {
rowData = $.parseJSON(response);
}
else {
alert("Retrive Error !!");
}
},
error: function (error) { }
});
return rowData;
}
/*
var paramstr = '';
paramstr = "#UserID$" + uid + '~';
paramstr += "#PageName$" + pgnm + '~';
*/
paramstr += "#MethodName$" + pgnm + '~';
paramstr += "#ErrorMsg$" + msg;
function fncCompareDates1(startDate, endDate) {
startDate = startDate.split('/');
endDate = endDate.split('/');
var new_start_date = new Date(startDate[2], startDate[1], startDate[0]);
var new_end_date = new Date(endDate[2], endDate[1], endDate[0]);
var date1 = startDate.split('/')[2] + "-" + startDate.split('/')[1] + "-" + startDate.split('/')[0];
var new_start_date = new Date(date1);
var date2 = endDate.split('/')[2] + "-" + endDate.split('/')[1] + "-" + endDate.split('/')[0];
var new_end_date = new Date(date2);
if (date_format(startDate) > date_format(endDate))
return false;
return true;
}
public static DataSet BIZ_LIST_DATA(ref string errString, SqlParameter[] parameters, string spname)
{
try
{
DataSet ds = new DataSet();
ds = DB_LIST_DATA(parameters, spname);
return ds;
}
catch (Exception ex)
{
errString = ex.Message;
}
return null;
}
public static DataSet DB_LIST_DATA(SqlParameter[] Params, string spName)
{
SqlConnection sqlCon = new SqlConnection(main.connectionStringICane());
try
{
DataSet ds = new DataSet();
if (sqlCon.State == ConnectionState.Closed)
{
sqlCon.Open();
}
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = sqlCon;
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.CommandText = spName;
foreach (SqlParameter p in Params)
{
if ((p.Direction == ParameterDirection.InputOutput) && (p.Value == null))
{
p.Value = DBNull.Value;
}
sqlCmd.Parameters.Add(p);
}
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCmd);
sqlDataAdapter.Fill(ds);
return ds;
}
catch (Exception ex)
{
throw ex;
}
finally
{
sqlCon.Close();
sqlCon.Dispose();
}
}
function get_cols(data) {
var datacols = [];
if (!isEmpty(data)) {
$.each(data.Table1, function (name, value) {
if (value.ColumnWidth == 0)
datacols.push({ text: value.ColumnHeader, datafield: value.DataField, hidden: true });
else
datacols.push({ text: value.ColumnHeader, datafield: value.DataField, cellsalign: 'left', align: 'left', width: value.ColumnWidth });
});
}
return datacols;
}
function isEmpty(str) {
return typeof str == 'string' && !str.trim() || typeof str == 'undefined' || str === null || str == 0 || str == "" || str == "[]";
}
function getRowData_TableBased(procName, paramstr, urlpath) {
var rowData = '';
$.ajax({
url: urlpath,
type: "POST",
dataType: "json",
async: false,
data: "{procedureName: '" + procName + "',paramstr: '" + paramstr + "'}",
contentType: "application/json; charset=utf-8",
success: function (data) {
rowData = data;
},
error: function (error) {
}
});
return rowData;
}
function Common_grid() {
var commonModuleOption = {
width: '97%',
height: '350',
filterable: true,
sortable: true,
theme: 'energyblue',
pageable: true,
columnsresize: true,
pagesizeoptions: ['5', '10', '15', '20', '100'],
pagesize: 15,
pagermode: 'default',
enabletooltips: true,
};
return commonModuleOption;
}
public ActionResult Commmon_Method(string VN, string Id)
{
return View(#"~/" + VN + ".cshtml");
}
public ActionResult Commmon_Method_Url()
{
return PartialView(#"~/" + Request.QueryString["VN"] + ".cshtml");
}
[HttpPost]
public ActionResult GetRowData_Tables(string paramstr, string procedureName)
{
#region
string[] parameters = paramstr.Split('~');
string err = string.Empty;
int len = parameters.Length;
SqlParameter[] sqlParam = new SqlParameter[len];
for (int i = 0; i < len; i++)
{
string[] paramWithValue = parameters[i].Split('$');
string param = paramWithValue[0].ToString();
string value = paramWithValue[1].ToString();
sqlParam[i] = new SqlParameter { ParameterName = param, Value = value };
}
return Content(Newtonsoft.Json.JsonConvert.SerializeObject(GetListData(ref err, sqlParam, procedureName), Newtonsoft.Json.Formatting.Indented));
#endregion
}
public DataSet GetListData(ref string errString, SqlParameter[] parameters, string spname)
{
#region
try
{
DataSet ds = new DataSet();
ds = ListData(parameters, spname);
return ds;
}
catch (Exception ex)
{
errString = ex.Message;
}
return null;
#endregion
}
public DataSet ListData(SqlParameter[] Params, string spName)
{
#region
String conString = System.Configuration.ConfigurationManager.ConnectionStrings["Connection2"].ConnectionString;
SqlConnection sqlCon = new SqlConnection(conString);
#region
try
{
DataSet ds = new DataSet();
if (sqlCon.State == ConnectionState.Closed)
{
sqlCon.Open();
}
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = sqlCon;
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.CommandText = spName;
foreach (SqlParameter p in Params)
{
if ((p.Direction == ParameterDirection.InputOutput) && (p.Value == null))
{
p.Value = DBNull.Value;
}
sqlCmd.Parameters.Add(p);
}
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCmd);
sqlDataAdapter.Fill(ds);
return ds;
}
catch (Exception ex)
{
throw ex;
}
finally
{
sqlCon.Close();
sqlCon.Dispose();
}
#endregion
#endregion
}
//[OutputCache(Duration = 3600, VaryByParam = "none")]
public ActionResult LoadMenus()
{
#region
#region
var cntent = "";
DataSet dsmenus = new DataSet();
string error = "";
SqlParameter[] parameters = { new SqlParameter("#usid", SqlDbType.Int) { Value = 6 } };
dsmenus = new DALModel().populateDataSet(ref error, parameters, "DBSP_Get_Menu");
StringBuilder sb = new StringBuilder();
#endregion
sb.Append("<ul id='main-menu' class='sm sm-vertical sm-blue' data-smartmenus-id='15544681331245752'>");
if (dsmenus.Tables[0].Rows[0]["MenuID"].ToString() == "0" && dsmenus.Tables[0].Rows[0]["ParentID"].ToString() == "0")
{
cntent = "<ul></ul>";
}
else
{
#region
var ds = dsmenus.Tables[0].AsEnumerable().Where(r => r.Field<Int32>("ParentID") == Convert.ToInt32("0"));
foreach (DataRow pdr in ds)
{
var MenuID = Convert.ToInt32(pdr["MenuID"].ToString());
var Action = pdr["Action"].ToString();
var Controller = pdr["Controller"].ToString();
var MenuDesc = pdr["MenuDesc"].ToString();
sb.Append("<li>");
if (Action == "")
sb.Append("<a href='#'>" + MenuDesc + "</a>");
else
//sb.Append("<a href='" + Url.Action(Action, Controller, new { MenuId = MenuID }) + "'>" + "" + MenuDesc + "" + "</a>");
sb.Append("<a href='" + Url.Action("Commmon_Method_Url", "Home", new { VN = Action, ID = MenuID }) + "'>" + "" + MenuDesc + "" + "</a>");
sb = getSubMenuList(MenuID, dsmenus, sb);
sb.Append("</li>");
}
#endregion
}
sb.Append("</ul>");
cntent = sb.ToString();
return Content(cntent, "text/html");
#endregion
}
[OutputCache(Duration = 3600, VaryByParam = "none")]
public StringBuilder getSubMenuList(Int32 ParentID, DataSet ds, StringBuilder sb)
{
#region
try
{
var sm = ds.Tables[0].AsEnumerable().Where(r => r.Field<Int32>("ParentID") == ParentID);
Int32 cnt = sm.AsDataView<DataRow>().Count;
if (cnt > 0)
{
#region
sb.Append("<ul>");
foreach (DataRow subdr in sm)
{
var MenuID = Convert.ToInt32(subdr["MenuID"].ToString());
var Action = subdr["Action"].ToString();
var Controller = subdr["Controller"].ToString();
string MenuDesc = subdr["MenuDesc"].ToString().Replace(" ", "-");
sb.Append("<li>");
if (Action == "")
sb.Append("<a href='#'>" + MenuDesc + "</a>");
else
//sb.Append("<a href='" + Url.Action(Action, Controller, new { MenuId = MenuID }) + "'>" + MenuDesc + "</a>");
sb.Append("<a href='" + Url.Action("Commmon_Method_Url", "Home", new { VN = Action, ID = MenuID }) + "'>" + MenuDesc + "</a>");
sb = getSubMenuList(MenuID, ds, sb);
sb.Append("</li>");
}
sb.Append("</ul>");
#endregion
}
else
{
return sb;
}
}
catch (Exception ex)
{
throw ex;
}
return sb;
#endregion
}
public ActionResult common_dll(string ctrl, string View)
{
#region
StringBuilder sb = new StringBuilder();
sb.Append("using System;" + Environment.NewLine);
sb.Append("using System.Collections.Generic;" + Environment.NewLine);
sb.Append("using System.Data;" + Environment.NewLine);
sb.Append("using System.Data.SqlClient;" + Environment.NewLine);
sb.Append("using System.Dynamic;" + Environment.NewLine);
sb.Append("using System.Linq;" + Environment.NewLine);
sb.Append("using System.Text;" + Environment.NewLine);
sb.Append("using System.Reflection;" + Environment.NewLine);
sb.Append("using System.Reflection.Emit;" + Environment.NewLine);
sb.Append("using System.Web.Mvc;" + Environment.NewLine);
sb.Append("namespace Testing_MVC.Controllers" + Environment.NewLine);
sb.Append("{" + Environment.NewLine);
sb.Append("public class " + ctrl + "Controller" + " : Controller" + Environment.NewLine);
sb.Append("{" + Environment.NewLine);
sb.Append("public ActionResult " + View + "()" + Environment.NewLine);
sb.Append("{" + Environment.NewLine);
sb.Append("return View();" + Environment.NewLine);
sb.Append("}" + Environment.NewLine);
sb.Append("}" + Environment.NewLine);
sb.Append("}" + Environment.NewLine);
#endregion
#region
var dir = Server.MapPath("~\\Controllers");
var file = System.IO.Path.Combine(dir, ctrl + "Controller" + ".cs");
/*
System.IO.FileInfo fi = new System.IO.FileInfo(file);
System.IO.StreamWriter str = fi.CreateText();
str.WriteLine(sb.ToString());
str.Close();
*/
//System.IO.Directory.CreateDirectory(dir);
//System.IO.File.WriteAllText(file, sb.ToString());
if (System.IO.File.Exists(file))
System.IO.File.Delete(file);
System.IO.File.AppendAllLines(file, sb.ToString().Split(Environment.NewLine.ToCharArray()).ToList<string>());
/*
System.IO.FileInfo fi = new System.IO.FileInfo(file);
System.IO.StreamWriter str = fi.CreateText();
str.WriteLine(sb.ToString());
str.Close();
*/
#endregion
return this.RedirectToAction(View, ctrl, new { MainID = 12, ID = 1 });
}
<script>
$('#btn_Test').click(function () {
window.location.href = '#Url.Action("common_dll", "Home")?ctrl=Testing&View=Index';
//window.location.href = '#Url.Action("Commmon_Method", "Home")?Id=' + 1 + '&VN=' + 'Areas/Testing/Views/Index';
});
</script>
<script>
//$(function () {
// var paramstr = '';
// paramstr = "##Month$" + 1;
// paramstr += "~##Year$" + 2018;
// paramstr += "~##StateID$" + 0;
// paramstr += "~##HubID$" + 0;
// paramstr += "~##BranchID$" + 0;
// paramstr += "~##EmpID$" + 0;
// paramstr += "~##EmpTypeID$" + 0;
// paramstr += "~##UserID$" + 1;
// paramstr += "~##UserTypeID$" + 1;
// var data = getRowData_TableBased('DBSP_MM_Rpt_AttendanceMonthWsie', paramstr, '#Url.Action("GetRowData_Tables", "Home")');
// Grid(data);
//});
function Grid(data) {
if (!isEmpty(data)) {
//$("#jqxgrid").jqxGrid($.extend(true, {}, Common_grid(), {
// source: { datatype: "json", datafields: [], localdata: data },
// columns: Get_Colmns(data)
//}));
}
}
function Get_Colmns(data) {
var datacols = [];
if (!isEmpty(data)) {
$.each(data.Table1, function (name, value) {
if (value.ColumnWidth == 0)
datacols.push({ text: value.ColumnHeader, datafield: value.DataField, hidden: true });
else
datacols.push({ text: value.ColumnHeader, datafield: value.DataField, cellsalign: 'left', align: 'left', width: value.ColumnWidth });
});
}
return datacols;
}
</script>
<script>
$('#btn_Controller1').click(function () {
window.location.href = '#Url.Action("common_dll", "Home")?ctrl=Testing&View=Index';
//window.location.href = '#Url.Action("Commmon_Method", "Home")?Id=' + 1 + '&VN=' + 'Views/Test/Index';
//window.location.href = '#Url.Action("common_dll", "Home")?ctrl=List&View=Index';
});
$('#btn_Controller2').click(function () {
window.location.href = '#Url.Action("common_dll", "Home")?ctrl=MyDocs&View=Test';
});
$('#btn_Controller3').click(function () {
window.location.href = '#Url.Action("common_dll", "Home")?ctrl=Test&View=Delete';
});
$('#btn_Controller4').click(function () {
window.location.href = '#Url.Action("common_dll", "Home")?ctrl=Test1&View=Index';
});
$('#btn_Controller5').click(function () {
window.location.href = '#Url.Action("common_dll", "Home")?ctrl=Test2&View=Index';
});
$('#btn_Controller6').click(function () {
window.location.href = '#Url.Action("common_dll", "Home")?ctrl=Test3&View=Index';
});
</script>
<body>
<form id="form1" modelAttribute="uploadForm" enctype="multipart/form-data">
<label for="sampleText">Please enter a text </label>
<input id="sampleText" name="sampleText" type="text" /> <br/>
,
<label for="sampleFile">Please select a file</label>
<input id="sampleFile" name="files[0]" type="file" style="border: solid 1px black" /> <br/>
<label for="sampleFile1">Please select a file</label>
<input id="sampleFile1" name="files[1]" type="file" style="border: solid 1px black" /> <br/>
<input id="uploadBtn" type="button" value="Ajax Submit" onClick="Checkfiles();"></input>
</form>
<script type="text/javascript">
function Checkfiles()
{
var fup = document.getElementById('sampleFile');
var fileName = fup.value;
var ext = fileName.substring(fileName.lastIndexOf('.') + 1);
if(ext == "gif" || ext == "GIF" || ext == "JPEG" || ext == "jpeg" || ext == "jpg" || ext == "JPG" || ext == "doc" || ext == "txt")
{
performAjaxSubmit();
}
else
{
alert("Upload Gif or Jpg images only");
fup.focus();
return false;
}
}
function performAjaxSubmit() {
var sampleText = document.getElementById("sampleText").value;
var sampleFile = document.getElementById("sampleFile").files[0];
var sampleFile1= document.getElementById("sampleFile1").files[1];
var formdata = new FormData();
formdata.append("files[0]", sampleFile);
formdata.append("files[1]", sampleFile1);
var xhr = new XMLHttpRequest();
xhr.open("POST","save.html", true);
xhr.send(formdata);
xhr.send(formdata);
}
</script>
in the controller side
#RequestMapping( value = "/save", method = RequestMethod.POST )
public String save( #ModelAttribute( "uploadForm" ) FileUploadForm uploadForm,
BindingResult result,
Model map ) throws IllegalStateException, IOException
{
List<MultipartFile> files = uploadForm.getFiles();
List<String> fileNames = new ArrayList<String>();
if( null != files && files.size() > 0 )
{
for( MultipartFile multipartFile : files )
{
if( multipartFile.getSize() > 0 )
{
}
InputStream inputStream = null;
inputStream = multipartFile.getInputStream();
if( multipartFile.getSize() > 10000 )
{
System.out.println( "File Size exceeded:::" + multipartFile.getSize() );
}
String fileName = multipartFile.getOriginalFilename();
fileNames.add( fileName );
System.out.println( fileName );
//Handle file content - multipartFile.getInputStream()
File dest = new File( "C:/Aslam/files/" + fileName );
multipartFile.transferTo( dest );
}
}
System.out.println( "save.html is called" );
map.addAttribute( "files",
fileNames );
return "file_upload_success";
}
The requirement is to use ajax with spring without submitting the form, but the problem in the above code is that files[1] is not saved,
I am not sure whats happening - either xhr is not passing the files[1] to the controller or controller is not reading the files[1]
Please somebody help me i am new to ajax
The following code worked for me using Apache file upload ..
In Javascript
var fd = new FormData();
fd.append('file',packageFile);
fd.append('file',xmlFile);
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.onreadystatechange = function() { });
xhr.send(fd);
In Spring contoller
public String save(HttpServletRequest request, HttpServletResponse httpServletResponse) {
boolean isMultipart;
String response = null;
String myFileName = null;
String filename = null;
isMultipart = ServletFileUpload.isMultipartContent(request);
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List fileItems = upload.parseRequest(request);
Iterator i = fileItems.iterator();
while (i.hasNext()) {
FileItem fi = (FileItem) i.next();
if (!fi.isFormField()) {
InputStream in = fi.getInputStream();
filename = UPLOAD_FILE_DIR + sessionId + "/" + fi.getName();
if (filename.endsWith(".zip")) {
myFileName = fi.getName();
} else if(filename.endsWith(".xml")) {
myFileName = fi.getName();
}
File fd = new File(UPLOAD_FILE_DIR + sessionId + "/" + myFileName);
final File parent_directory = fd.getParentFile();
FileOutputStream fos = new FileOutputStream(fd);
byte[] buffer = new byte[4096];
int length;while ((length = in.read(buffer)) > 0) {
fos.write(buffer, 0, length);
}
fos.close();
}
}
EDIT: The following is the Javascript code to get the selected files and adding them to FormData
packageFile = $.find(".fileselector")[0].files[0];
xmlFile = $.find(".fileselector")[1].files[0];
var fd = new FormData();
fd.append('file',packageFile);
fd.append('file',xmlFile);
Following is my XMLHttpRequest
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.onreadystatechange = function() { });
xhr.send(fd);
Below is the HTML tags for uploading files
<input id="upf_local_fileinput1" type="file" name="myFile" path="fileData" class="fileselector">
<input id="upf_local_fileinput2" type="file" name="myFile" path="fileData" class="fileselector">
Try the below code if you still have problem because I remember that in some version of Spring the above code didn't worked.
MultipartHttpServletRequest multi = (MultipartHttpServletRequest) request;
Map fileMap = multi.getFileMap();
Iterator fileIt = fileMap.keySet().iterator();
while (fileIt.hasNext()) {
String fileKey = (String) fileIt.next();
MultipartFile file = (MultipartFile) fileMap.get(fileKey);
if (file != null) {
bufReader = new BufferedReader(new InputStreamReader(file.getInputStream()));
} else {
System.out.println("Invalid file");
}
String str;
File file = new File(imeiFilePath);
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
while ((str = bufReader.readLine()) != null) {
if (bw != null) {
bw.write(str);
bw.newLine();
}
}
if (bw != null) {
bw.flush();
bw.close();
}
}
hi guys sorry i m really new to mvc3 javascript jquery etc.
i have an internal server error 500
this is the controller:
[HttpGet]
public JsonResult GetEmail(string title, string notes)
{
byte[] pdf = null;
byte[] excel = null;
string userEmail = "";
try
{
pdf = GetFileForMail("PDF", "ServiceArea_" + System.DateTime.Now.ToString("yyyyMMdd_HHmmss") + ".pdf", title, notes);
excel = GetFileForMail("EXCEL", "ServiceArea_" + System.DateTime.Now.ToString("yyyyMMdd_HHmmss") + ".xls", title, notes);
MembershipUser mu = Membership.GetUser(this.MembershipData.Principal.Identity.Name);
userEmail = mu.Email.ToString();
System.Net.Mail.MailMessage mailMsg = new System.Net.Mail.MailMessage(userEmail,
"mailexample#mail.com",
title,
notes);
mailMsg.To.Add("no-replay#valuelab.it");
mailMsg.IsBodyHtml = true;
string mese = "";
string giorno = "";
string ore = "";
if (DateTime.Now.Month < 10)
mese = "0" + DateTime.Now.Month;
else
mese = "" + DateTime.Now.Month;
if (DateTime.Now.Day < 10)
giorno = "0" + DateTime.Now.Day;
else
giorno = "" + DateTime.Now.Day;
if(DateTime.Now.Hour < 10)
ore = "0" + DateTime.Now.Hour;
else
ore = "" + DateTime.Now.Hour;
System.Net.Mail.Attachment att = new System.Net.Mail.Attachment(new MemoryStream(pdf), DateTime.Now.Year + mese + giorno + "_" + ore + DateTime.Now.Minute + " Report.pdf", System.Net.Mime.MediaTypeNames.Application.Pdf);
System.Net.Mail.Attachment att2 = new System.Net.Mail.Attachment(new MemoryStream(excel), DateTime.Now.Year + mese + giorno + "_" + ore + DateTime.Now.Minute + " Report.xls", "application/vnd.ms-excel");
mailMsg.Attachments.Add(att);
mailMsg.Attachments.Add(att2);
System.Net.Mail.SmtpClient sc = new System.Net.Mail.SmtpClient();
sc.Host = "192.168.99.1";
sc.Send(mailMsg);
return Json(new { text = "Everything is fine " + userEmail, risultato = true });
}
catch (Exception e) {
return Json(new { text = "Unexpected error" + userEmail , risultato = false});
}
}
and this is the way in which i call the controller:
jQuery.ajax({
type: "GET",
url: options.EmailUrl,
dataType: "json",
data:
{
title: viewModel.saReportTitle(),
notes: viewModel.saReportNotes()
},
success: function (data, textStatus, jqXHR) {
jQuery("#sa-dialog-alert").dialog('open');
jQuery("#sa-dialog-alert").dialog('option', 'title', 'Invio Mail Eseguito');
jQuery("#sa-dialog-alert").text(data.text);
}
,
error: function (data, textStatus, errorThrown) {
jQuery("#sa-dialog-alert").dialog('open');
jQuery("#sa-dialog-alert").dialog('option', 'title', 'Errore');
jQuery("#sa-dialog-alert").text("Errore nell'invio mail: " + errorThrown);
}
});
If you read the code the controller just send an email
and IT WORK FINE THERE are no exception
so why ajax say there is a 500 internal server error?
By default GET requests are not allowed on JsonResult so you need to excplicitly allow them, with setting the JsonRequestBehavior property:
return Json(
new { text = "Everything is fine " + userEmail, risultato = true },
JsonRequestBehavior.AllowGet
);
Or use POST as your request method in your AJAX call.