Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Question
Monday, July 13, 2015 2:45 PM
i am able to save the data to a file on my pc, but cannot make the Save file dialog appear. Am expecting the winforms style, but of course that doesnt work here in mvc
here is the code, which takes the modified openxml document and saves it directly to a hard wired location:
protected void btnDownload_Click(object sender, EventArgs e)
{
byte[] byteArray = (byte[])(Session["ByteArray"]);
if (byteArray != null)
{
Response.Clear();
Response.ContentType = "application/octet-stream";
string fileName = (string)(Session["FileNameFromUser"]);
Response.AddHeader("Content-Disposition",
String.Format("attachment; filename={0}", fileName));
Response.BinaryWrite(byteArray);
Response.Flush();
Response.End();
}
else
{
lblMessage.Text = "You have not specified a file.";
}
}
Now since I already defined the byte array and modified it, i just want to use that,
Response.Clear();
Response.ContentType = "application/octet-stream";
string fileNamewrite =(string) (Session["FileNameFromUser"]);
Response.AddHeader("Content-Disposition", String.Format("attachment; filename={0}",fileNameout));
Response.BinaryWrite(mem.ToArray());
Response.Flush();
Response.End();
this is within the method that changed the data, when it runs it correctly saves the word.docx modified document to the pc, it opens and works great; what it DOES NOT DO is make any kind of savefile dialog
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
saveFileDialog1.FilterIndex = 2;
saveFileDialog1.RestoreDirectory = true;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
Response.Clear();
Response.ContentType = "application/octet-stream";
string fileNamewrite =(string) (Session["FileNameFromUser"]);
Response.AddHeader("Content-Disposition", String.Format("attachment; filename={0}",fileNameout));
Response.BinaryWrite(mem.ToArray());
Response.Flush();
Response.End();
}
ERROR: there is no such thing as SaveFileDialog at all, in any way, ever, anywhere. this appears to be not permitted from mvc. cannot just call save file dialog. The type or namespace name 'SaveFileDialog' could not be found (are you missing a using directive or an assembly reference?)
I have about 40 "using" statements up there, half are probably not needed.
how do files get saved from an mvc app?
All replies (17)
Tuesday, July 14, 2015 9:25 PM âś…Answered
Hi,
You have another option to save the file first using a stream writer.
I have created a simple codes below ASP.NET MVC 4.0; you can copy and paste change the path; and it should work.
HTML
@using (Html.BeginForm("YourAction", "Home", FormMethod.Post))
{
@Html.AntiForgeryToken()
<input type="submit" value="Save File Now" />
}
Your Controller
[HttpPost]
public ActionResult YourAction()
{
HttpResponse response = System.Web.HttpContext.Current.Response;
HttpResponse resp = System.Web.HttpContext.Current.Response;
string filename = "thisfilename.txt";
string destFolder = @"D:\NET\MvcApplication2\MvcApplication2\temp";
string filePath = Path.Combine(destFolder, filename);
using (StreamWriter writer = new StreamWriter(filePath))
{
writer.Write("Word ");
writer.WriteLine("word 2");
writer.WriteLine("Line");
writer.Flush();
writer.Close();
}
resp.ContentType = "application/text";
resp.AppendHeader("content-disposition", "attachment; filename=" + "thisfilename.txt");
response.WriteFile(filePath);
response.Flush();
response.End();
return View();
}
Monday, July 13, 2015 4:07 PM
SaveFileDialog is on server side, not on client side( on your PC is the same... however, think about deployment)
You use
<input type='file'
Monday, July 13, 2015 4:21 PM
HI
I dont understand. I was hoping to implement on the server side within the Create controller.
when the code modifies the openxml document, it should directly send a save file dialog to the user to get the literal path. and yes its running on an iis server, I cannot use savefiledialog because there is no reference for it, it will not compile. what is there that does the savefile dialog function for mvc?
Monday, July 13, 2015 4:34 PM
using <input type='file'
this causes an OPEN file dialog box but nothing i could do makes a save file dialog
Monday, July 13, 2015 6:43 PM
Yeah, it will not work. The code is running on the server not the client.
Monday, July 13, 2015 10:59 PM
so youre saying it CAN made an open file dialog, but its impossible to make a save file dialog? just wanting to get clarification. it seems that if one dialog could be made to come up that any of them could;
Monday, July 13, 2015 11:01 PM
should i try to get a bootstrap add in? or what do you suggest as an alternative to this?
Monday, July 13, 2015 11:23 PM
so youre saying it CAN made an open file dialog, but its impossible to make a save file dialog? just wanting to get clarification.
An <input type=file is for file upload to a web server. This is a browser function and has been around for a long long time.
it seems that if one dialog could be made to come up that any of them could;
It's just not how browsers work and it's not how the web works. The code you are trying to invoke is running on the server. Even if you were able to get it to work the dialog would pop up on the server not the client.
Monday, July 13, 2015 11:38 PM
Hi,
I think you are on the right direction.
Can you try changing from BinaryWrite to WriteFile?
response.WriteFile(mem.ToArray());
I have tried this a lot of times; this should open a file save dialog to the client machine.
Tuesday, July 14, 2015 12:58 AM
nothing i could do makes a save file dialog
for this you will send a file to the user. This can be done returning a FileContent
Tuesday, July 14, 2015 11:36 AM
Hi Gio
it will not let me. it will not do WriteFile like this: byte[] memory stream.toarray() error: the best overloaded method match for system.web.httpresponsebase.writefile(string) has some invalid arguments
Server Error in '/' Application.
Could not find a part of the path 'C:\Users\test\Downloads\Project3.MNM\Project3.zip\Project3\test11\DocGEN2\System.Byte[]'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
if I try a response.write(mem.toarray()) it crashes the reference DocumentFormatOpenXml, which must be deleted then re installed
Tuesday, July 14, 2015 11:38 AM
rogersbr
nothing i could do makes a save file dialog
for this you will send a file to the user. This can be done returning a FileContent
I cannot find FileContent, but can find FileContentResult ? which does not work either it runs but no save file dialog
Tuesday, July 14, 2015 2:50 PM
In order for the browser to prompt the user to save the file, you must send the following headers in the response.
Content-Type: application/octet-stream;
Content-Transfer-Encoding: binary;
See this stack overflow thread. While it is PHP, the same concept applies to ASP.
http://stackoverflow.com/questions/11315951/using-the-browser-prompt-to-download-a-file
Tuesday, July 14, 2015 4:19 PM
thanks for the suggestion, but no it keeps downloading direct and does not open any save dialog;
so far i cannot find the 'binary' version Response.HeaderEncoding:Base64BinaryValue; nope
but am already doing Response.BinaryWrite(mem.ToArray());
which is a binary write? then i changed it to this still doesnt work right:
Response.Clear();
FileInfo file = new FileInfo(fileNameout);
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.TransmitFile(file.FullName);
// string fileNamewrite = (string)(Session["FileNameFromUser"]);
// Response.AddHeader("Content-Disposition", String.Format("attachment; filename={0}", fileNameout));
Response.Flush();
Response.End();
and it still just quickly writes the file to the hardwired path, never asks for a save file dialog path
Wednesday, July 15, 2015 1:45 AM
I cannot find FileContent, but can find FileContentResult ? which does not work either it runs but no save file dialog
It works . Show the code.
Wednesday, July 15, 2015 8:41 AM
**EDITED:: the problem was somewhere else. the browser setting was directly saving the file, it would not ask for saveFileAs. apparently trying several ways it probably would have put the dialog if my browser was not set to save to the /Downloads folder without asking. **
i created a method called GetFile of type FileContentResult. with all this code it still just sends the file directly, run it and the file just downloads and show up on the pc in the hard wired location. If trying to use FileContent it is red underlined, when typing the type FileContent shows the filecontentresult, hit space and this is filled in.
ignatandrei is this what you are referring to in FileContent??
public FileContentResult GetFile(byte[] m)
{
string mimeType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
string filenam = "output.docx";
byte[] fileContent = null;
fileContent = m; //["FileContent"];
///////////////////////////
Response.Clear();
FileInfo file = new FileInfo(fileNameout);
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.TransmitFile(file.FullName);
// string fileNamewrite = (string)(Session["FileNameFromUser"]);
// Response.AddHeader("Content-Disposition", String.Format("attachment; filename={0}", fileNameout));
Response.Flush();
Response.End();
return File(fileContent, mimeType, filenam); //pass contents as bytes[] , your mimetype , and the file name save as.
}
Wednesday, July 15, 2015 10:02 AM
I am referring to this:
https://msdn.microsoft.com/en-us/library/system.web.mvc.filecontentresult(v=vs.118).aspx
However, if it works , it is ok.