I Put The Download Link in jqgrid, my Files are Stored on server not in database, files are of different types(extension)
i want user should download file when he clicks on download link
Code For Loading jqgrid is as Follws
public object GetJSONFormatProjectDetails(List<ProjectMasterDTO> listProjectDTO, int SkipCount)
{
var data = (listProjectDTO.Select(c => new
{
id = c.ProjectID,
cell = new[]
{
c.ProjectName,
c.OfficeName,
c.ProjectType,
c.ProjectNature,
c.EntrepreneurName,
c.Year + " Years " +c.Month + " Months " + c.Day + " Days" ,
c.ConcessionWEFdate,
c.ProjectStartDate,
c.ProjectEndDate,
c.isRoadApplicable,
(c.FilePath != "NA" ) ? "<a href='#' style='color:green' onclick='DownLoadFile(\""+URLEncrypt.EncryptParameters(new string[]{ "filepath =" +c.FilePath.Replace("/","$").Replace(" ","#").Trim()})+"\");return false;'>"+(c.FilePath != "NA" ? "DownLoad":"Not Available") + " </a>" : "<span style='color:Red' >Not Available</span>"
}
})).ToArray().Skip(SkipCount);
return data;
}
JS File Code is As Follows
function DownLoadFile(param) {
$.ajax({
url: "/Home/GetFile?parameter=" + param,
cache: false,
type: "POST",
async: false
});
}
Code in Controller as follows
public ActionResult GetFile(string parameter)
{
string queryStringParameters = Request.QueryString["parameter"];
if (queryStringParameters == null)
{
throw new Exception("Url is tampered");
}
string[] parameterArray = queryStringParameters.Split('/');
string param = null;
string hash = null;
string key = null;
if (parameterArray.Length == 3)
{
param = parameterArray[0];
hash = parameterArray[1];
key = parameterArray[2];
}
if (!(string.IsNullOrEmpty(parameter)))
{
Dictionary<string, string> parameters = URLEncrypt.DecryptParameters(new string[] { param, hash, key });
string FilePath =string.Empty ;
parameters.TryGetValue("filepath", out FilePath);
FilePath = FilePath.Replace('$','\\');
// DownloadFile(FilePath);
string name = Path.GetFileName(FilePath);
string ext = Path.GetExtension(FilePath);
string type = "";
// set known types based on file extension
if (ext != null)
{
switch (ext.ToLower())
{
case ".pdf":
type = "Application/pdf";
break;
case ".doc":
case ".docx":
type = "Application/msword";
break;
case ".jpg":
case ".bmp":
case ".tiff":
case ".png":
case ".gif":
case ".jpeg":
type = "Application/Image";
break;
default:
type = "Application";
break;
}
}
Response.AppendHeader("content-disposition", "attachment; filename=" + name);
if (type != "")
{
Response.ContentType = type;
}
String FullFilePath = #"F:\MHTOLL\ContractUploadDetails\" + name;
//return File(new FileStream(path + fileName, FileMode.Open), "text/plain", fileName);
// return File(new FileStream(FullFilePath, FileMode.Open), type, name);
return File(FullFilePath, type,name);
}
return null;
}
Dont mind now about return null and exception handling
also suggest for displaying .gif animation for downloading file.
I don't think you can use an AJAX call to download a file.
I think this answer will get you what you want. Be sure to read the comments about the download prompt and MIME types. Download File Using Javascript/jQuery
I recently encountered the same issue and realized that AJAX will not work to download a file. Try an ActionLink instead:
#Html.ActionLink("ButtonName", "controllerFunctionName", "controllerName", new { functionParamName = paramValue })
And you would include your function in the controller:
public ActionResult controllerFunctionName(type functionParamName){
// do your download here
}
Related
Im really struggling to get SummerNote to upload an iamge in .NET core. The trouble is the IFormFile file parameter is null when a new image is uploaded.
I initialise Summernote using the following -
$('#MessageBody').summernote({
height: ($(window).height() - 300),
callbacks: {
onImageUpload: function(image) {
uploadImage(image[0]);
}
}
});
Here is the uploadImage function -
function uploadImage(image) {
var data = new FormData();
data.append("image", image);
$.ajax({
url: '/EmailTemplate/UploadImage',
cache: false,
contentType: false,
processData: false,
data: data,
type: "post",
success: function(url) {
var image = $('<img>').attr('src', 'http://' + url);
$('#MessageBody').summernote("insertNode", image[0]);
alert(url);
var imgNode = document.createElement('img');
imgNode.src = url;
$('#MessageBody').summernote('insertNode', imgNode);
},
error: function(data) {
console.log(data);
}
});
And finally, here is the controller -
[HttpPost]
public async Task<IActionResult> UploadImage(IFormFile file)
{
string message;
var saveimg = Path.Combine(_hostingEnvironment.WebRootPath, "Images", file.FileName);
string imgext = Path.GetExtension(file.FileName);
if (imgext == ".jpg" || imgext == ".png")
{
using (var uploadimg = new FileStream(saveimg, FileMode.Create))
{
await file.CopyToAsync(uploadimg);
message = "The selected file" + file.FileName + " is saved";
}
}
else
{
message = "only JPG and PNG extensions are supported";
}
// return "filename : " + saveimg + " message :" + message;
return Content(Url.Content(saveimg));
}
The parameter is called file while the field name is image. To fix this use the same name, either file or image.
The IFormFile type represents the value of an input type=file field. IFormFile parameters are bound to fields based on their name. There may be many file fields in the same form so the type isn't enough to determine the field.
Field binding is explained in the Sources section of the Model Binding document.
This is my update, i added a debugging point at the ImageUrl null check and even tho there is already an ImageUrl it says its null
ublic IActionResult Upsert(ProductVM obj,IFormFile file)
{
if (ModelState.IsValid)
{
string wwwRootPath = _hostEnvironment.WebRootPath;
if (file != null)
{
string fileName = Guid.NewGuid().ToString();
var uploads = Path.Combine(wwwRootPath, #"Images\products");
var extention = Path.GetExtension(file.FileName);
if (obj.Product.ImageUrl != null)
{
var oldImagePath = Path.Combine(wwwRootPath,obj.Product.ImageUrl.TrimStart('\\'));
if (System.IO.File.Exists(oldImagePath))
{
System.IO.File.Delete(oldImagePath);
}
}
using (var fileStreams = new FileStream(Path.Combine(uploads, fileName + extention), FileMode.Create))
{
file.CopyTo(fileStreams);
}
obj.Product.ImageUrl = #"\Images\products\" + fileName + extention;
}
if (obj.Product.Id == 0)
{
_unitOfWork.Product.Add(obj.Product);
}
else
{
_unitOfWork.Product.Update(obj.Product);
}
_unitOfWork.Save();
TempData["success"] = "Produs adaugat cu succes!";
return RedirectToAction("Index");
}
return View(obj);
}
enter image description here
Go to your upsert view:
Insert hidden field on your view:
<input asp-for="Product.ImageUrl" hidden />
Insert this on the upsert view
I created a web app using asp.net-mvc and Jquery
when I added the below code my application automatically stop running without throwing any error, I don't know Whether it is my visual studio 19 or IIS which is being crashed
<label for="myfile">Select a file:</label>
<input type="file" id="myfile" name="myfile">
To verify I created an asp.net mvc sample project and paste the above code in the index page but the same problem comes
Image
what can I do to solve this?
Do you have
enctype="multipart/form-data"
property in your form element?
<form id="upload">
<input type="file" id="file" class="form-control">
</form>
Jquery
$('#upload').submit(function (e) {
e.preventDefault(); // stop the standard form submission
var File_Name = $("#file").prop('files')[0].name;
var ext = File_Name.split('.').pop();
if (ext == "pdf" || ext == "docx" || ext == "doc" || ext == "png" || ext ==
"jpg" || ext == "jpeg" || ext == "txt") {
var lastIndex = $("#file").prop('files')[0].name.lastIndexOf(".") + 1;
var form = new FormData();
form.append("file", $("#file").prop('files')[0]);
$.ajax({
url: '/Main/SaveDocument',
type: 'POST',
data: form,
cache: false,
contentType: false,
processData: false,
success: function (data) {
console.log(data.UploadedFileCount + ' file(s) uploaded successfully');
if (data == "999") {
swal("Note", "Some Error Occurred. File Not uploaded successfully.", "error");
}
},
error: function (xhr, error, status) {
console.log(error, status + " " + xhr);
}
});
}
else {
swal("Note", "File Type Not Supported.", "warning");
}
});
C#
public ActionResult SaveDocument()
{
//file
var file = System.Web.HttpContext.Current.Request.Files["file"];
var CheckCnic = hr_FTPEntities.File_description.Where(x => x.uploader_CNIC == userCNIC).FirstOrDefault();
if(CheckCnic == null)
{
HttpPostedFileBase filebase = new HttpPostedFileWrapper(file);
if (filebase.ContentLength > 0)
{
var fileName = Path.GetFileName(filebase.FileName);
string path = Path.Combine(Server.MapPath(basePath + departmentName) + "/");
File_description file_Description = new File_description();
int fileCount = hr_FTPEntities.File_description.Select(x => x).ToList().Count + 1;
int lastIndexOfDot = fileName.LastIndexOf(".") - 1;
string finalFileName = fileName.Substring(0, lastIndexOfDot) + "_" + fileCount + fileName.Substring(lastIndexOfDot + 1);
file_Description.file_name = finalFileName.ToString();
try
{
filebase.SaveAs(path + (finalFileName));
}
catch(Exception ex)
{
return Json("999");
}
}
return Json("000");
}
else
{
return Json("888");
}
}
You could try to use the below code:
View(Index.cshtml) :
<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', 'test');
$.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>
Controller (HomeController.cs):
[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.");
}
}
Make sure your IIS site contains the upload folder and enough permission to access the folder.
If you still face the same issue then try to use the different browser.
check event viewer logs or try to collect the dup and analyze the dump using the DebugDiag tool.
In my view, I have checkboxes and some data displayed and button on each row to approve or reject requests put up.
I want to send my integer array to my action method but this cannot be done by just sending it to action query parameters and it would be like the picture below:
public int[] Ids
{
get { return new int[] { 1, 2, 3 }; }
set {}
}
public ActionResult Approval([ModelBinder(typeof(IntArrayModelBinder))] int[] ids)
{
...
return View(...);
}
#Html.ActionLink("Approve", "Approval", new {id = item.Ids, approvalAction = "approve"})
How do I implement the checkboxes to be checked and hover of the approve/reject actionlink will show the url with ../ids=1&ids=2&ids=3 instead of System.Int32[]?
Option 1: Send your array as a comma-separated string and then split them in your action like this :
#Html.ActionLink("Approve", "Approval", new { id = string.Join("," , Ids), approvalAction = "approve" } )
your action :
public ActionResult YourAction(string id , string approvalAction)
{
var ids = id.Split(',');
//rest of your action method business
}
Option 2:
another way to achieve your exactly url is to create your URL like this :
var baseUrl = Url.Action("YourAction", "YourController", null, Request.Url.Scheme);
var uriBuilder = new UriBuilder(baseUrl);
uriBuilder.Query = string.Join("&", Ids.Select(x => "ids=" + x));
string url = uriBuilder.ToString();
url += "&approvalAction=approve"
and your action would be like this :
public ActionResult YourAction(int[] ids , string approvalAction)
{}
<script>
function multiSelect(selectedArray, action) {
if (selectedArray[0] === undefined) {
alert("You have not selected any employee");
}
//example url
//..?ids=1&ids=2&ids=3&aprovalAction=approve
else {
var param = "";
var currUrl = "";
var idUrl = "";
idUrl = "ids=" + selectedArray[0];
for (var i = 1; i < selectedArray.length; ++i) {
idUrl += "&ids=" + selectedArray[i];
}
switch (action) {
case "Approve":
param = "approve";
break;
case "Reject":
param = "reject";
break;
}
currUrl = "approvalAction=" + param;
window.location.href = "?" + idUrl + "&" + currUrl;
}
}
</script>
<script>
$('#MultiApproveBtn').click(function () {
var selected = $('input[type=checkbox]:checked').map(function (_, el) {
return $(el).val();
}).get();
var x = document.getElementById("MultiApproveBtn").value;
//alert(selected);
multiSelect(selected, x);
})
</script>
<script>
$('#MultiRejectBtn').click(function () {
var selected = $('input[type=checkbox]:checked').map(function (_, el) {
return $(el).val();
}).get();
var x = document.getElementById("MultiRejectBtn").value;
//alert(selected);
multiSelect(selected, x);
})
</script>
i am using ajax call to save data and print the receipt.
My ajax call is
$.ajax({
type: "POST",
url: "/Payments/AddPayment",
data: frm,
dataType: "json",
success: function (objData) {
//ResetFormData();
if (objData.AMENDEDBY == "") {
strMsg = "Added Sucessfully";
}
else {
strMsg = "Updated Sucessfully";
}
AlertData(strMsg, "Payments", "success");
window.location.assign("/Report/PrintReport?objData=" + objData.REFNO);
}
});
Data saved accurately and after that i want to take print of the saved data.
i am using
window.location.assign("/Report/PrintReport?objData=" + objData.REFNO);
my Controller code for pritn crystal report is
public ActionResult PrintReport(string objData)
{
try
{
//Report Object
ReportDocument rd = new ReportDocument();
rd.Load(Path.Combine(Server.MapPath("~/Reports/Accounts"), "CrystalReport1.rpt"));
rd.RecordSelectionFormula = "{TBL_ACC_VOUCHERS_MASTER.REFNO}='" + objData + "'";
//Report Connection object
ReportRepo objReport = new ReportRepo();
rd = objReport.GetReportConnections(rd);
//Print Report Direct to Default Printer
PrintDocument pdoc = new PrintDocument();
string PrinterName = pdoc.PrinterSettings.PrinterName;
rd.PrintOptions.PrinterName = PrinterName;
rd.PrintToPrinter(1, true, 0, 0);
return new EmptyResult();
}
catch
{
throw;
}
}
Report printed successfully but as return i am getting default view with reset values. I want to get the same view without any change.
i also used
return Redirect(HttpContext.Request.UrlReferrer.AbsoluteUri);
but same result