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.
Related
I am getting below error when trying to upload a file to a folder:
System.InvalidOperationException: 'The entity type Document is not
part of the model for the current context.'
Here is the code:
public ActionResult AddHRDocument()
{
DocumentsConn db = new DocumentsConn();
return View();
}
[HttpPost]
public ActionResult AddHRDocument(HttpPostedFileBase file)
{
//Extract Image File Name.
string fileName = System.IO.Path.GetFileName(file.FileName);
//Set the Image File Path.
string filePath = "~/Documents/HR/" + fileName;
//Save the Image File in Folder.
file.SaveAs(Server.MapPath(filePath));
//Insert the Image File details in Table.
DocumentsConn db = new DocumentsConn();
db.Documents.Add(new Document
{
DocumentName = fileName,
Document_url = filePath
});
db.SaveChanges();
}
This error is very generic, it could have a number of reasons.
1-The problem may be in the connection string. Ensure your connection
string is for SqlClient provider, with no metadata stuff related to
EntityFramework.
2-Make sure that you are not explicitly ignoring the type:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Ignore<Document>();
}
3-There is a problem with naming to map entity to table name:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Doucment>().ToTable("Doucment");
}
I used this code for upload multi files.you can edit your code for 0ne file.
View : Write enctype = "multipart/form-data"
#using (Html.BeginForm("ActionName", "ControolerName", FormMethod.Post, new { enctype = "multipart/form-data" }))
UploadFile Box:
#Html.TextBoxFor(Model => Model.Files, new { type = "file", name = "Files", multiple = "multiple", #class = "form-control", accept = "image/*" })
use below code in your action for get files from request:
[HttpPost]
public ActionResult UploadFile(long Id)
action input parameter not necessary HttpPostedFileBase .
for (int i = 0; i < Request.Files.Count; i++)
{
var file = Request.Files[i];
string fileName = Guid.NewGuid() + System.IO.Path.GetExtension(file.FileName)?.ToLower();
string path = Server.MapPath("~") + "Files\\UploadImages\\" + fileName;
//TODO: Fill Properties Table.example: DocType Or Id Or AddressFile
// entity.DocType = System.IO.Path.GetExtension(file.FileName)?.ToLower();
if (File.DocType?.ToLower() == ".png" || File.DocType?.ToLower() == ".img"
|| File.DocType?.ToLower() == ".jpeg"
|| File.DocType?.ToLower() == ".jpg")
{
file.SaveAs(path);
//TODO: Save Info File In Database
}
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));
}
I have multiple pdf documents that I have to show in a view .My code is opening the same document for all the links which is wrong.
In my contoller :
public ActionResult Docs()
{
var docModel = this._documentBuilder.Build(this.StateData);
foreach (var doc in docModel.OldEstimateFiles)
{
return this.File(doc.PdfUrl, "application/pdf");
}
return null;
}
and in the view :
foreach (var menuItem in Model.OldEstimateFiles)
{
<ul >
<li>
#using (Html.Anchor(new ststyle { URL = "/DocumentEstimate/Docs", Target = "_blank", Text = menuItem.Label }))
{
}
</li>
</ul>
}
what is wrong in my code knowing that oldestimatefiles is a list
I edited my action in the controller to take in the ID.
public ActionResult Docs(string id)
{
var docModel = this._documentBuilder.Build(this.StateData);
return docModel.OldEstimateFiles.Any() ? this.File(docModel.OldEstimateFiles.Find(p => p.ID == id).PdfUrl, "application/pdf") : null;
}
I added an entry in the routeConfig file taking in the URL the id of the document and In the view I edited my link :
#using (Html.Anchor(new ststyle
{
URL = "/DocumentEstimate/EstimateDocs/" + menuItem.ID,
Id = menuItem.ID
It resolved the issue.
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
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()">