Download .txt file from another server into local (ASP MVC) - asp.net-mvc

I have successfully download file from my local into my local in ASP MVC.
View
#using (Html.BeginForm("Download", "Home", FormMethod.Post))
{
<button class="btn btn-primary" >Download</button>
}
controller
public ActionResult Download()
{
string file = #"C:\Users\Xin\Desktop\test.txt";
string contentType = "text/plain";
return File(file, contentType, Path.GetFileName(file));
}
What I want to ask is, how to do it if the file is not in my local, but it is on different server? let say server name called VUP-1 and the path on the server is C:\Users\Xin\Documents\test.txt

You are going to download files from Server where you have kept files.
You can used Server.MapPath and pass file path.
public ActionResult Download()
{
string file = Server.MapPath("~/Files/Demo.txt");
string contentType = "text/plain";
return File(file, contentType, Path.GetFileName(file));
}

Related

How to open Pdf in Browser and Save as Pdf file in Folder in Asp.net mvc

I want to use the opening Pdf file, and the User inputs some of the fields and then saves this file into the Specific folder in my Asp.net folder.
I try to use the HttpPostedFileBase file but I cannot save this file to a folder, always become null for Parameter. Is it working right? You guys have any other idea for open Pdf and edit, save as pdf file to a folder?
<form method="post" enctype="multipart/form-data">
<div>
<embed name="file" src="~/AnnounceFile/PDF.pdf"
style="width: 780px; height:980px;"
class="with-200" />
<button type="submit">Import</button>
</div>
</form>
Controller
[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
string filename = Guid.NewGuid() + Path.GetExtension(file.FileName);
string filepath = "/folder/" + filename;
file.SaveAs(Path.Combine(Server.MapPath("/excelfolder"), filename));
InsertExceldata(filepath, filename);
return View(db.Iteminfoes.ToList());
}
You can open the pdf using target="_blank" in a href tag
File Name
The PDFHelper.GeneratePDF is returning array of bytes of PDF file. As I understood, after that you need to store this PDF in local folder. In that case you can use.
protected void save_pdf()
{
String path_name = "~/PDF/";
var pdfPath = Path.Combine(Server.MapPath(path_name));
var formFieldMap = PDFHelper.GetFormFieldNames(pdfPath);
string username = "Test";
string password = "12345";
String file_name_pdf = "Test.pdf";
var pdfContents = PDFHelper.GeneratePDF(pdfPath, formFieldMap);
File.WriteAllBytes(Path.Combine(pdfPath, file_name_pdf), pdfContents);
WebRequest request = WebRequest.Create(Server.MapPath("~/PDF/" + pdfContents));
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(username, password);
Stream reqStream = request.GetRequestStream();
reqStream.Close();
}
Also, please see Can a Byte[] Array be written to a file in C#?

Image not displaying in ASP.NET MVC

In an ASP.NET MVC application, file is successfully saved to a folder and its URL is saved to SQL database. Having problem in loading file in a browser from folder using this URL. Code implementation is:
[HttpPost]
[ActionName("UploadPhoto")]
public ActionResult UploadPhoto(HttpPostedFileBase photoPath)
{
var fileName = Path.GetFileName(photoPath.FileName);
string path;
if (photoPath.ContentLength > 0)
{
path = Path.Combine(Server.MapPath("~/Images/photos"), fileName);
photoPath.SaveAs(path);
return RedirectToAction("CreateWithImage", new { path = path });
}
return View();
}
public ActionResult CreateWithImage(string path)
{
employee em = new employee();
em.districts = new SelectList(hc.districts, "name", "name");
em.photoPath = path;
return View(em);
}
file (image) is rendered in a view as:
#model HRMS.Models.employee
<dd>
#Html.Image(#Model.photoPath)
</dd>
Extension method implementation for #Html.Image is:
namespace HRMS.CustomeHTMLHelper
{
public static class CustomHtmlHelper
{
public static IHtmlString Image(this HtmlHelper helper,string src)
{
TagBuilder tb = new TagBuilder("img");
tb.Attributes.Add("src", VirtualPathUtility.ToAbsolute(src));
return new MvcHtmlString(tb.ToString(TagRenderMode.SelfClosing));
}
}
}
When View is called, I see a broken link for the image. HTML(with correct file path) for the loaded page (View) is seen as:
<dd>
<img src="/App_Data/photos/1.png" />
</dd>
When I try to run the physical path to the image in the browser i.e., <b>Requested URL</b> http://localhost:57852/App_Data/photos/1.png, it is throwing HTTP Error 404.8 - Not Found Error.
Where could I be wrong? Please help.

File Upload in MVC 5

I am developing a MVC 5 application and using MS SQL Server as a database. I have form in this app, which will store the event details in database. in this form i have a file upload field. Actually i want to upload an image in a folder on the server and store its URL in the database so that URL could be used in my front end.
Following is my create action method
public ActionResult Create([Bind(Include = "Id,Event_Name,Event_Description,Event_Detail,Image_Url,Event_Date,User_Name,Date_Uploaded,Category_ID")] WASA_Events wASA_Events)
{
var filePath = FileUpload();//Function call to get the uploaded file path
wASA_Events.Image_Url = filePath;
if (ModelState.IsValid)
{
db.WASA_Events.Add(wASA_Events);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.Category_ID = new SelectList(db.WASA_Events_Category, "id", "Event_Category", wASA_Events.Category_ID);
return View(wASA_Events);
}
and FileUpload Function which will return the file path is as under
public string FileUpload()
{
var filePath = "";
if(Request.Files.Count > 0)
{
var file = Request.Files[0];
if(file!=null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/images/uplods/"), fileName);
file.SaveAs(path);
filePath = path;
}
}
return (filePath);
}
and in my view i used the following
#using (Html.BeginForm("Create", "WASA_Events", FormMethod.Post, new { enctype = "multipart/form-data" }))
Now the problem is i got nothing in the Request.Files.Count, means its value is zero. So can't move ahead.
Any Help.
Check the below.,.,
Check whether you can get the files in the request in the Create Action itself. I am sure that the request will maintain state in the FileUpload method too. But check for if it's not.
Whether the file upload input is inside the form that you are using in the view ?
Whether the file upload input is any third party control ? If so, check if you have the file name is updated in the file upload input in the HTML after selecting the file in the browser.
A little crazy check would be whether you have selected a file and opted to upload the file in the browser.,.,
I just did the file upload by adding the following class
public class Pictures
{
public HttpPostedFileBase File { get; set; }
}
and then use it in my create Controller action method. Below is the code for controller action
if (picture.File.ContentLength > 0)
{
var fileName = Path.GetFileName(picture.File.FileName);
var path = Path.Combine(Server.MapPath("~/assets/uploads/events/"), fileName);
picture.File.SaveAs(path);
}
and in view
<input type="file" id="File" name="File" class="form-control"/>
this solvedmy problem

How to download a file to client from server?

I have an MVC project where I'd like the user to be able to download a an excel file with a click of a button. I have the path for the file, and I can't seem to find my answer through google.
I'd like to be able to do this with a simple button I have on my cshtml page:
<button>Button 1</button>
How can I do this? Any help is greatly appreciated!
If the file is not located inside your application folders and not accessible directly from the client you could have a controller action that will stream the file contents to the client. This could be achieved by returning a FileResult from your controller action using the File method:
public ActionResult Download()
{
string file = #"c:\someFolder\foo.xlsx";
string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
return File(file, contentType, Path.GetFileName(file));
}
and then replace your button with an anchor pointing to this controller action:
#Html.ActionLink("Button 1", "Download", "SomeController")
Alternatively to using an anchor you could also use an html form:
#using (Html.BeginForm("Download", "SomeController", FormMethod.Post))
{
<button type="submit">Button 1</button>
}
If the file is located inside some non-accessible from the client folder of your application such as App_Data you could use the MapPath method to construct the full physical path to this file using a relative path:
string file = HostingEnvironment.MapPath("~/App_Data/foo.xlsx");
HTML:
<div>#Html.ActionLink("UI Text", "function_name", "Contoller_name", new { parameterName = parameter_value },null) </div>
Controller:
public FileResult download(string filename) {
string path = "";
var content_type = "";
path = Path.Combine("D:\file1", filename);
if (filename.Contains(".pdf"))
{
content_type = "application/pdf";
}
return File(path, content_type, filename);
}

Download file from link inside my webpage

I have Webpage with table of objects.
One of my object properties is the file path, this file is locate in the same network. What i want to do is wrap this file path under link (for example Download) and after the user will click on this link the file will download into the user machine.
so inside my table:
#foreach (var item in Model)
{
<tr>
<th width ="150"><p><b>Download</b></p></th>
<td width="1000">#item.fileName</td>
<td width="50">#item.fileSize</td>
<td bgcolor="#cccccc">#item.date<td>
</tr>
}
</table>
I created this download link:
<th width ="150"><p><b>Download</b></p></th>
I want this download link to wrap my file path and click on thie link will lean to my controller:
public FileResult Download(string file)
{
byte[] fileBytes = System.IO.File.ReadAllBytes(file);
}
What i need to add to my code in order to acheive that ?
Return FileContentResult from your action.
public FileResult Download(string file)
{
byte[] fileBytes = System.IO.File.ReadAllBytes(file);
var response = new FileContentResult(fileBytes, "application/octet-stream");
response.FileDownloadName = "loremIpsum.pdf";
return response;
}
And the download link,
Download
This link will make a get request to your Download action with parameter fileName.
EDIT: for not found files you can,
public ActionResult Download(string file)
{
if (!System.IO.File.Exists(file))
{
return HttpNotFound();
}
var fileBytes = System.IO.File.ReadAllBytes(file);
var response = new FileContentResult(fileBytes, "application/octet-stream")
{
FileDownloadName = "loremIpsum.pdf"
};
return response;
}
In the view, write:
Download
In the controller, write:
public FileResult DownloadFile(string file)
{
string filename = string.Empty;
Stream stream = ReturnFileStream(file, out filename); //here a backend method returns Stream
return File(stream, "application/force-download", filename);
}
This example works fine for me:
public ActionResult DownloadFile(string file="")
{
file = HostingEnvironment.MapPath("~"+file);
string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
var fileName = Path.GetFileName(file);
return File(file, contentType,fileName);
}
View:
< script >
function SaveImg()
{
var fileName = "/upload/orders/19_1_0.png";
window.location = "/basket/DownloadFile/?file=" + fileName;
}
< /script >
<img class="modal-content" id="modalImage" src="/upload/orders/19_1_0.png" onClick="SaveImg()">

Resources