I want to allow users to choose a file to download from a drop down list. Once they have made a selection, they can click the download button. However, the file does not download correctly.
Here is the controller for generating and returning the file:
[HttpPost]
public ActionResult DownloadReport(int? id, string templateChoice)
{
if (id == null)
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
try
{
byte[] file = GetReport(id, templateChoice);
return File(file, "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "ResumeReport.docx");
}
catch (InvalidOperationException)
{
return View();
}
}
The JavaScript function which is called upon pressing the generate report button is:
function downloadReport(InputID) {
$.ajax({
type: 'POST',
url: '#Url.Action("DownloadReport", "UserProfiles")',
data: JSON.stringify({ "ID": InputID, "TemplateChoice": $("#resumeTemplates").val() }),
contentType: 'application/json; charset=utf-8'
});
}
Opening the inspect window in chrome and going to the network tab shows the document data is received, but it does not download like a regular file.
I seemed to have found a working solution which does not reload page, does not redirect the user, and does not show any excess text in the URL upon pressing the download button. I replaced my current JavaScript function with the following:
function downloadReport(inputID) {
window.location.href = '/UserProfiles/DownloadReport/?id=' + inputID + '&template=' + $('#resumeTemplates').val();
}
And my controller now looks like:
public ActionResult DownloadReport(int? id, string template)
{
if (id == null || template == null)
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
try
{
byte[] file = GetReport(id, template);
return File(file, "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "ResumeReport.docx");
}
catch (InvalidOperationException)
{
return View();
}
}
I also added this into my RouteConfig.cs file:
routes.MapRoute(
"DownloadReport",
"{controller}/{action}/{id}/{template}",
new { controller = "UserProfiles", action = "DownloadReport", id = UrlParameter.Optional, template = UrlParameter.Optional }
);
Related
I am trying to download an excel file generated from data entered through a webpage in an MVC application.
This ajax call is executed when a button is pressed, and calls two methods in my controller. One to generate the excel file and another to download the file:
$.ajax({
type: 'POST',
data: myDataObject,
url: 'MyController/GenerateExcel/',
success: function(data) {
if (data.id != "") {
$http.get('MyController/DownloadExcel?id=' + encodeURIComponent(data.id) + '&name=' + encodeURIComponent(data.name));
return true;
}
}
});
Here is my POST method that generates the excel file and saves it to TempData:
[HttpPost]
public JsonResult GenerateExcel(Object model)
{
var fileName = "myexcel.xlsx";
var fileID = Guid.NewGuid().ToString();
var generatedReport = GenerateCustomExcel(model);
using (MemoryStream memoryStream = new MemoryStream())
{
generatedReport.SaveAs(memoryStream);
generatedReport.Dispose();
memoryStream.Position = 0;
TempData[fileID] = memoryStream.ToArray();
}
return Json(new { id = fileID, name = fileName });
}
Here is my GET method that downloads the saved excel from TempData:
[HttpGet]
public FileResult DownloadExcel(string id, string name)
{
if (TempData[id] != null)
{
byte[] fileBytes = TempData[id] as byte[];
return File(fileBytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", name);
}
else
{
return null;
}
}
This works flawlessly in Google Chrome and Firefox browsers. However, when using either Internet Explorer or Microsoft Edge browsers, the file refuses to download.
The debug console doesn't produce any useful errors. I have tried changing the returned File type to an octet stream and using window.location.href instead of a get request to download the file, but nothing appears to work. All of the functions are called and data passed between them correctly, so routes are not the problem.
Does anyone know how I can make the returned FileResult download?
Here is a solution. It uses the same code as in my question except for the changes listed here.
Add an iframe element to your webpage:
<iframe id="iFrameFileDownload" style="display: none;"></iframe>
In the javascript, instead of a call using $http.get(), set the 'src' attribute of the iframe element to the controller function url:
$.ajax({
type: 'POST',
data: myDataObject,
url: 'MyController/GenerateExcel/',
success: function(data) {
if (data.id != "") {
$("#iFrameFileDownload").attr("src", 'MyController/DownloadExcel?id=' + encodeURIComponent(data.id) + '&name=' + encodeURIComponent(data.name));
return true;
}
}
});
Another solution that I considered is using the window.open() function instead of $http.get(). (source: Download a file with mvc) However, that solution uses popups and would require users to enable popups in their browser before downloading the file.
I am using ASP.Net Core with MVC for creating an app. I am using visual studio and IIS express currently.
Below is my current project structure:
*project directory
-wwwroot
-areas
-attachments
-controllers
-models
-views
I currently store images inside the attachments folder.
Previously I have written something like that inside my startup.cs
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(
Path.Combine(Directory.GetCurrentDirectory(), "Attachments")),
RequestPath = "/Attachments"
});
I have also done something like this below:
appendImage(#Url.Content("~/Attachments/")+result.fileName);
I did this to display an image on my view. The image is displayed successfully.
What I am trying to achieve now is the on the UI allow the user to make a choice to delete the files inside that attachments folder
I tried the following code:
string contentRootPath = _hostingEnvironment.ContentRootPath;
string fullImagePath = Path.Combine(contentRootPath + "\\Attachments", currentItemToDelete.FileName);
if (System.IO.File.Exists(fullImagePath))
{
try{
System.IO.File.Delete(fullImagePath);
}catch(Exception e){
operationResult = "Attachment Path. Internal Server Error";
}
}
The execution does enter the if (System.IO.File.Exists(fullImagePath))
but it raises an exception when it reaches System.IO.File.Delete. The exception states that the file which resides in that path is being used by another process. And thus I cannot delete the file. The only process that is accessing the file is the web app I am creating/debugging at the same time. How do I prevent this exception from happening? Do I have to use other kind of code to delete the file ?
EDIT to include more details:
Inside my view(index.cshtml):
appendImage is a javascript function:
function appendImage(imgSrc) {
var imgElement = document.createElement("img");
imgElement.setAttribute('src', imgSrc);
if (imgSrc.includes(null)) {
imgElement.setAttribute('alt', '');
}
imgElement.setAttribute('id', "img-id");
var imgdiv = document.getElementById("div-for-image");
imgdiv.appendChild(imgElement);
}
That function is called below:
$.ajax({
url:'#Url.Action("GetDataForOneItem", "Item")',
type: "GET",
data: { id: rowData.id },
success: function (result) {
removeImage();
appendImage(#Url.Content("~/Attachments/")+result.fileName);
$("#edit-btn").attr("href", '/Item/EditItem?id=' + result.id);
},
error: function (xhr, status, error) {
}
});
After calling appendImage(); I change the href of a <a> tag. When the user clicks on the link, the user is directed to another page(edit.cshtml). In the page, the image which resides in that path is also being displayed with code like this:
<img src="#Url.Content("~/Attachments/"+Model.FileName)" alt="item image" />
In this new page(edit.cshtml), there is a delete button. Upon clicking the delete button, the execution of the program goes to the controller which is this controller function:
[HttpPost]
public string DeleteOneItem(int id)
{
//query the database to check if there is image for this item.
var currentItemToDelete = GetItemFromDBDateFormatted(id);
if (!string.IsNullOrEmpty(currentItemToDelete.FileName))
{
//delete the image from disk.
string contentRootPath = _hostingEnvironment.ContentRootPath;
string fullImagePath = Path.Combine(contentRootPath + "\\Attachments", currentItemToDelete.FileName);
if (System.IO.File.Exists(fullImagePath))
{
try
{
System.IO.File.Delete(fullImagePath);
}catch(Exception e)
{
}
}
}
return "";
}
EDIT to answer question:
Add in
System.GC.Collect();
System.GC.WaitForPendingFinalizers();
before system.io.file.delete
you can replace your C# method DeleteOneItem with this given code. may be it might work.
[HttpPost]
public string DeleteOneItem(int id)
{
//query the database to check if there is image for this item.
var currentItemToDelete = GetItemFromDBDateFormatted(id);
if (!string.IsNullOrEmpty(currentItemToDelete.FileName))
{
//delete the image from disk.
string contentRootPath = _hostingEnvironment.ContentRootPath;
string fullImagePath = Path.Combine(contentRootPath + "\\Attachments", currentItemToDelete.FileName);
if (System.IO.File.Exists(fullImagePath))
{
try
{
System.GC.Collect();
System.GC.WaitForPendingFinalizers();
System.IO.File.Delete(fullImagePath);
}
catch (Exception e) { }
}
}
return "";
}
try
{
System.GC.Collect();
System.GC.WaitForPendingFinalizers();
System.IO.File.Delete(fullImagePath);
}
catch(Exception e){
}
I'm trying to continuously display the contents of a file on my HTML page
(at every 'X' times). In other words, I want to make a logger and visualize it as if it were in a terminal. I'm new to AJAX and I'm not exactly sure how to set up the ajax call in the javascript, more specifically, what URL goes by parameter.
I'm passing a model through my controller to a form in thymeleaf:
<form id="formTest" class="form-inline" action="#" th:action="#{'log/'}" th:object="${log}" method="post">
...
</form>
This way I can create an object and then print its contents. The contents of the object originate from a file*.log*, which is located in a remote directory.
<p th:utext="${log.content}">Log content</p>
The file path is mapped in the controller
#RequestMapping(value = "/log", method = RequestMethod.POST)
public String logContent_post(#Valid Log log, BindingResult bindingResult, Map<String, Object> model) {
if (log.getInitLine() == 0 && log.getFinalLine() == 0) {
try {
fileNumberLines(log);
// lineOccurrence, firstLine, lastLine, logPath
log.setContent(getLogContentByRange(0, log.getInitLine(), log.getFinalLine(), logsDir + "/" + log.getFilename()));
} catch (IOException e) {
logger.error(e.getMessage());
}
} else {
log.setContent(
getLogContentByRange(0, log.getInitLine(), log.getFinalLine(), logsDir + "/" + log.getFilename()));
}
model.put("path", logsDir);
model.put("log", log);
model.put("currentPage", "logs");
model.put("root", root);
return "log";
}
My Ajax function
function att(){
$.ajax({
type : 'POST',
url : '',
cache: false,
success : function(data) {
console.log("Content:" + data);
},
complete : function() {
}
});
}
setInterval(function() {
if (window.location.pathname == '/log/') {
att();
}
}, 5000);
I've tried to pass several "url's" through AJAX, but either I get 404 () or null as a return. So my question: What Url should I pass by parameter?
I am working a jQuery file upload helper and I need to understand how can I append the File from the form or the Form data as a whole to the request.
I have worked with the ASP.NET code to accept image from the Request and handle the further code, but when I try to use it using jQuery $.ajax() I can't get it to work.
I have been though Stack Overflow questions, and I have tried using FormData appending the data from the input[type="file"] (input for the file element). But each time (on the server) the block that is executed that tells me there is no file with the request.
Here is the ASP.NET code (UploadFile page)
#{
var fileName = "Not running!";
if(IsPost) {
if(Request.Files.Count > 0) {
var image = WebImage.GetImageFromRequest();
fileName = Path.GetFileName(image.FileName) + " From server";
} else {
fileName = "No file attached! From Server";
}
}
Response.Write(fileName);
}
The jQuery code is as
$(document).ready(function () {
$('form input[type=submit]').click(function () {
event.preventDefault();
$.ajax({
url: '/UploadFile',
data: new FormData().append('file',
document.getElementById("image").files[0]),
type: 'POST',
success: function (data) {
$('#result').html('Image uploaded was: ' + data);
}
});
});
});
I am already scratching my head since I can't get the file content on the serverside.
How can I send the file to the server, or the entire form data to the server, anything would be welcome!
Try using handler for this and Newtonsoft.json.dll for these purpose.
For jQuery
(document).ready(function () {
$('form input[type=submit]').click(function () {
event.preventDefault();
$.ajax({
url: 'handler.ashx', // put a handler instead of direct path
data: new FormData().append('file',
document.getElementById("image").files[0]),
type: 'POST',
success: function (data) {
$('#result').html('Image uploaded was: ' + data);
}
});
});
});
In asp.net
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Web;
using Newtonsoft.Json;
public class Handler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
HttpPostedFile up = context.Request.Files[0];
System.IO.FileInfo upinfo = new System.IO.FileInfo(up.FileName);
System.Drawing.Image upimg = System.Drawing.Image.FromStream(up.InputStream);
string path = context.Server.MapPath("~/temp"); // this is the server path where you'll be saving your image
if (!System.IO.Directory.Exists(path))
System.IO.Directory.CreateDirectory(path);
string fileName;
fileName = up.FileName;
string newFilename = Guid.NewGuid().ToString();
System.IO.FileInfo fInfo = new System.IO.FileInfo(fileName);
newFilename = string.Format("{0}{1}", newFilename, fInfo.Extension);
string strFileName = newFilename;
fileName = System.IO.Path.Combine(path, newFilename);
up.SaveAs(fileName);
successmsg1 s = new successmsg1
{
status = "success",
url = "temp/" + newFilename,
width = upimg.Width,
height = upimg.Height
};
context.Response.Write(JsonConvert.SerializeObject(s));
}
Valums file-uploader (now called Fine Uploader) doesn't work under Internet Explorer 9 but wors fine under Chrome.
So under IE it shows the name of the file and button CANCEL and no % of uploading.
Any clue?
UPDATES:
Solution is here as well MVC Valums Ajax Uploader - IE doesn't send the stream in request.InputStream
I know this question was filed under asp.net specifically, but it came up when I searched for "valums ajax upload IE9", so I'll post my fix here in case it helps anyone like myself regardless of language:
I was returning a JSON response from the AJAX upload request with a "application/json" content header. IE9 does not know what to do with "application/json" content (but Chrome/FF/etc do).
I fixed this by making sure to return a "text/html" MIME type http header on my json response from the server.
Now IE is no longer trying to download the response! Cheers
I am unable to reproduce the issue. Here's a full working example.
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Upload(HttpPostedFileBase qqfile)
{
var uploadPath = Server.MapPath("~/app_data");
if (qqfile != null)
{
var filename = Path.Combine(uploadPath, Path.GetFileName(qqfile.FileName));
qqfile.SaveAs(filename);
return Json(new { success = true }, "text/html");
}
else
{
var filename = Request["qqfile"];
if (!string.IsNullOrEmpty(filename))
{
filename = Path.Combine(uploadPath, Path.GetFileName(filename));
using (var output = System.IO.File.Create(filename))
{
Request.InputStream.CopyTo(output);
}
return Json(new { success = true });
}
}
return Json(new { success = false });
}
}
Index.cshtml view:
<script src="#Url.Content("~/Scripts/valums/fileuploader.js")" type="text/javascript"></script>
<div id="file-uploader">
<noscript>
<p>Please enable JavaScript to use file uploader.</p>
</noscript>
</div>
<script type="text/javascript">
var uploader = new qq.FileUploader({
element: document.getElementById('file-uploader'),
action: '#Url.Action("upload")'
});
</script>
You could also include the CSS in your Layout:
<link href="#Url.Content("~/Scripts/valums/fileuploader.css")" rel="stylesheet" type="text/css" />
It seems that is IE cache issue, if you are using Ajax & GET, add timestamp value in the get parameters for the Ajax parameters, that will do the trick like this :
$.ajax({
url : "http:'//myexampleurl.php' + '?ts=' + new Date().getTime(),
dataType: "json",
contentType: "application/json; charset=utf-8",
.
.
//more stuff
If you are using java spring
#RequestMapping(value = "/upload", method = RequestMethod.POST, produces = "application/json")
public #ResponseBody YourObject excelUplaod(#RequestHeader("X-File-Name") String filename, InputStream is) {
// chrome or firefox
}
#RequestMapping(value = "/upload", method = RequestMethod.POST,headers="content-type=multipart/*", produces = "text/html")
public #ResponseBody ResponseEntity<YourObject> uploadByMultipart(#RequestParam(value = "qqfile") MultipartFile file) {
// IE
try {
String fileName = file.getOriginalFilename();
InputStream is = file.getInputStream();
// more stuff
} catch (Exception e) {
logger.error("error reading excel file", e);
}
}