ASP.NET MVC - How to dowload the .wmv file into our local file - asp.net-mvc

How to download the file from server file to out local file system of type (.wmv) video file using Asp.net MVC pattern.
The files are existed in the Server File system in a cetain folder. The correponding file name existed in our local database.
Using Server's file system path + filename(.wmv) have to store into my local file system. please send me the links or code.

In your controller:
public void Open()
{
var serverfilepath = "some logical path";
var filename = "some file name";
Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);
Response.ContentType = "video/x-ms-wmv";
Response.Charset = "utf-8";
Response.HeaderEncoding = UnicodeEncoding.UTF8;
Response.ContentEncoding = UnicodeEncoding.UTF8;
var fi = new FileInfo(serverfilepath);
if ( fi.Exists )
{
using( var fs = fi.OpenRead() )
{
// you should really buffer this...
var bytes = new byte[fs.Length];
fs.Read(bytes, 0, (int)fs.Length);
Response.BinaryWrite(bytes);
}
}
Response.End();
}

Related

PDFSharp download file thru filestream

I am new to this library but I couldn't find anything about downloading to the filestream with this library, I could only find a document.Save(filepath) option which is not always allowed.
I would like to create a filestream so the file gets downloaded to the directed Downloads folder.
Could someone point me in the right direct?
There is a Save overload that takes a MemoryStream object instead of path to a file.
The PDFSharp website has an example showing how to do this:
private void Page_Load(object sender, System.EventArgs e)
{
// Create new PDF document
PdfDocument document = new PdfDocument();
this.time = document.Info.CreationDate;
document.Info.Title = "PDFsharp Clock Demo";
document.Info.Author = "Stefan Lange";
document.Info.Subject = "Server time: " +
this.time.ToString("F", CultureInfo.InvariantCulture);
// Create new page
PdfPage page = document.AddPage();
page.Width = XUnit.FromMillimeter(200);
page.Height = XUnit.FromMillimeter(200);
// Create graphics object and draw clock
XGraphics gfx = XGraphics.FromPdfPage(page);
RenderClock(gfx);
// Send PDF to browser
MemoryStream stream = new MemoryStream();
document.Save(stream, false);
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("content-length", stream.Length.ToString());
Response.BinaryWrite(stream.ToArray());
Response.Flush();
stream.Close();
Response.End();
}

can eml directly open with outlook, instead eml file will download then click it to open in outlook?

I have an asp.net MVC application, below code works file.
But the code is that, When navigate to Email action in browser, an EML file is download, then when we click on that file, the file will open with outlook.
Can it be possible, when action calls, then EML file will directly open with outlook, instead of download and then click to open??
Code
public async Task<FileStreamResult> Email()
{
string dummyEmail = "test#localhost.com";
var mailMessage = new MailMessage();
mailMessage.From = new MailAddress(dummyEmail);
mailMessage.To.Add("dejan.caric#gmail.com");
mailMessage.Subject = "Test subject";
mailMessage.Body = "Test body";
// mark as draft
mailMessage.Headers.Add("X-Unsent", "1");
// download image and save it as attachment
using (var httpClient = new HttpClient())
{
var imageStream = await httpClient.GetStreamAsync(new Uri("http://dcaric.com/favicon.ico"));
mailMessage.Attachments.Add(new Attachment(imageStream, "favicon.ico"));
}
var stream = new MemoryStream();
ToEmlStream(mailMessage, stream, dummyEmail);
stream.Position = 0;
return File(stream, "message/rfc822", "test_email.eml");
}
private void ToEmlStream(MailMessage msg, Stream str, string dummyEmail)
{
using (var client = new SmtpClient())
{
var id = Guid.NewGuid();
var tempFolder = Path.Combine(Path.GetTempPath(), Assembly.GetExecutingAssembly().GetName().Name);
tempFolder = Path.Combine(tempFolder, "MailMessageToEMLTemp");
// create a temp folder to hold just this .eml file so that we can find it easily.
tempFolder = Path.Combine(tempFolder, id.ToString());
if (!Directory.Exists(tempFolder))
{
Directory.CreateDirectory(tempFolder);
}
client.UseDefaultCredentials = true;
client.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;
client.PickupDirectoryLocation = tempFolder;
client.Send(msg);
// tempFolder should contain 1 eml file
var filePath = Directory.GetFiles(tempFolder).Single();
// create new file and remove all lines that start with 'X-Sender:' or 'From:'
string newFile = Path.Combine(tempFolder, "modified.eml");
using (var sr = new StreamReader(filePath))
{
using (var sw = new StreamWriter(newFile))
{
string line;
while ((line = sr.ReadLine()) != null)
{
if (!line.StartsWith("X-Sender:") &&
!line.StartsWith("From:") &&
// dummy email which is used if receiver address is empty
!line.StartsWith("X-Receiver: " + dummyEmail) &&
// dummy email which is used if receiver address is empty
!line.StartsWith("To: " + dummyEmail))
{
sw.WriteLine(line);
}
}
}
}
// stream out the contents
using (var fs = new FileStream(newFile, FileMode.Open))
{
fs.CopyTo(str);
}
}
}
With Chrome you can make it automatically open certain files, once they are downloaded.
.EML should attempt to open in Outlook.
I am not sure about other browsers, but Chrome seemed to be the only one with this option.
It's not a pefect solution because if someone downloaded an .EML from another website in Chrome, it will open automatically aswell.
I recommend having Chrome dedicated to your Web application.
You sure can open local .eml file with Outlook.
But in context of web application, you must firstly download it.

How to make the .xlsx file download

The below is used to create the .xls file and download the file.
I want to download it to .xlsx file. If i simply change the extension into ".xlsx", the report directly opens in the browser. I want it to open in .xlsx extension. Kindly help me.
Below is the code reference for you,
//setting the application path to a variable
strPath = Server.MapPath("ExcelFiles");
//Creating a file name
strExportPath = "Card" + intRnd.ToString() + intRnd1.ToString() + ".xls";
hidFilePath.Value = "ExcelFiles/" + strExportPath;
//Creating the full path with the filename
strExcelPath = strPath + "\\" + strExportPath;
Session["AK_SC_CRD_EXCEL_PATH"] = strExcelPath;
StreamWriter objStreamWriter = new StreamWriter(strExcelPath, true);
//Write the XL Contents to a stream writer.
objStreamWriter.WriteLine(strXLContents);
objStreamWriter.Close();
objStreamWriter = null;
Thanks.
You may need to add a MIMETYPE for xslx to your response.
.xlsx,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
Similar to below;
Response.ContentType =
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Adding Following code will force your file download instead of opening in the browser.
Response.AddHeader("content-disposition", "attachment;filename=yourfilename.xlsx");
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
/*Add your code here to write file to response stream*/
Response.End();
Use following code to download Excel:-
HttpContext context = HttpContext.Current;
FileStream fs = null;
BinaryReader br = null;
byte[] data = null;
try
{
if (File.Exists(filePath))
{
FileInfo file = new FileInfo(filePath);
fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
br = new BinaryReader(fs, System.Text.Encoding.Default);
data = new byte[Convert.ToInt32(fs.Length)];
br.Read(data, 0, data.Length);
context.Response.Clear();
context.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
context.Response.AddHeader("content-disposition", "attachment; filename=" + file.FullName);
context.Response.AddHeader("Content-Length", file.Length.ToString());
context.Response.BinaryWrite(data);
context.Response.Flush();
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}

Error in File downloading file from a folder in MVC2

I am encountering a problem in getting the download prompt. In the below code first am allowing the user to upload a file to compress. Once the file is compressed the user should be provided with the compressed files. But in the below code download prompt doesn't appears neither it shows any error. Please help me by correcting my code
The view code:
function CompressFile(box) {
var file = document.getElementById('fileComp');
if (file.value == "") {
alert("Choose a file to upload");
return false;
}
dhtmlx.modalbox.hide(box);
var fd = new FormData();
fd.append('file', file.files[0]);
var xhr = new XMLHttpRequest();
xhr.open('POST', '/FileUpload/Compress', true);
xhr.send(fd);
}
The controller code:
public ActionResult Compress(HttpPostedFileBase file)
{
var supportedType = new[] { "pdf" };
var fileExt = System.IO.Path.GetExtension(file.FileName).Substring(1);
var filename = Path.GetFileNameWithoutExtension(file.FileName) ?? "";
if (file.ContentLength > 0 && supportedType.Contains(fileExt))
{
string filePath = Path.Combine(HttpContext.Server.MapPath(_uploadPDF), Path.GetFileName(file.FileName));
file.SaveAs(filePath);
PdfReader reader = new PdfReader(filePath);
string name = DateTime.Now.ToString("ddMM_HHmmss");
name = Server.MapPath(_fileUploadPath + name + ".pdf");
PdfStamper stamper = new PdfStamper(reader, new FileStream(name, FileMode.Create), PdfWriter.VERSION_1_5);
stamper.FormFlattening = true;
stamper.SetFullCompression();
stamper.Close();
string fn = System.IO.Path.GetFileName(name);
return base.File(name, "application/pdf",fn);
}
else
{
return View();
}
}
The problem is that you're using Ajax. You can't download a file through Ajax. You need to do a regular POST to the ActionMethod. That way the browser can send you back the file and prompt the user where he wants to save it.

Download functionality MVC 4

I have created a web api which connects users to dropbox via OAuth. I am using an API to interact with Dropbox, which works locally as I would like, however when I deploy the API to my Azure server, I am unable to download. I had anticipated this would happen, as my API is currently hard codded to a path on my machine.
Here is the method I am using:
NOTE: I call this method through an ActionResult, as part of the MVC portion of my project
public FileSystemInfo DownloadFile(string root, string path)
{
var uri = new Uri(new Uri(DropboxRestApi.ApiContentServer),
String.Format("files?root={0}&path={1}",
root, UpperCaseUrlEncode(path)));
var oauth = new OAuth();
var requestUri = oauth.SignRequest(uri, _consumerKey, _consumerSecret, _accessToken);
var request = (HttpWebRequest) WebRequest.Create(requestUri);
request.Method = WebRequestMethods.Http.Get;
var response = request.GetResponse();
var metadata = response.Headers["x-dropbox-metadata"];
var file = ParseJson<FileSystemInfo>(metadata);
using (Stream responseStream = response.GetResponseStream())
using (MemoryStream memoryStream = new MemoryStream())
{
byte[] buffer = new byte[1024];
int bytesRead;
do
{
bytesRead = responseStream.Read(buffer, 0, buffer.Length);
memoryStream.Write(buffer, 0, bytesRead);
} while (bytesRead > 0);
file.Data = memoryStream.ToArray();
}
return file;
}
This is where I call the method in my action result.
var file = api.DownloadFile("dropbox", "Public/downloadThis.jpg");
path = file.Path;
file.Save(#"....\Desktop\DemoTest\Downloads\downloadThis.jpg"); --- this is the problem & *Save* is a stream writer
Is there a procedure to follow when downloading files from a server on a browser?
public ActionResult download(Models.downloadModel dowld, Models.LoggerView log)
{
string TC_ID = Request.QueryString["id"].ToString();
string filename = TC_ID+"_LoggerData" + ".zip";
Response.ContentType = "application/octet-stream";
Response.AppendHeader("Content-Disposition", "attachment;filename=" + filename);
Response.TransmitFile(Server.MapPath("~/files/" + filename));
Response.End();
}

Resources