I'm trying to upload image to my folder and the display it in view.
My controller:
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
if (file != null)
{
string pic = System.IO.Path.GetFileName(file.FileName);
string path = System.IO.Path.Combine(Server.MapPath("~/images"), pic);
file.SaveAs(path);
ViewBag.Path = path;
}
return View();
}
My view:
#{
ViewBag.Title = "Upload";
}
#using (Html.BeginForm("Upload", "Home", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
<label for="file">Upload Image:</label>
<input type="file" name="file" id="file" style="width: 100%;" />
<input type="submit" value="Upload" class="submit" />
}
<h2>Upload</h2>
<img src="#ViewBag.path" alt="Image"/>
By doing this, image is not in my view, only alt text. HTML source generated:
<img src="C:\Users\D Stag\Documents\Visual Studio 2012\Projects\Data\Web\images\1232743916lituviai23afp.jpg"/>
Image is saved correctly, it exist in that folder.
Instead of -
ViewBag.Path = path;
try that this way -
ViewBag.Path = String.Format("/images/{0}", pic); //output should be "~/images/image1.jpg"
UPDATE: There is no need for "~" in the path. Then image displays.
Example Try like this:
<img src="#string.Format("/Image/{0}",pictue._id.ToString())" alt="#pictue.FileName" />
Related
I have tried this code but I'm unable to save the image/file in the specified folder. What is wrong with the code?
Controller:
public ActionResult Work(Work workmodel, HttpPostedFileBase workpostpath)
{
if (workpostpath != null)
{
// Upload your service images
using (entities = new saabinteriormodel())
{
string workpic = System.IO.Path.GetFileName(workpostpath.FileName);
string workpath = System.IO.Path.Combine(Server.MapPath("~/Content/Images/work/"), workpic);
workpostpath.SaveAs(workpath);
Work work = new Work
{
work_image = "~/Content/Images/work/" + workpic};
workmodel.work_image = work.work_image;
entities.Works.Add(work);
entities.SaveChanges();
}
}
return View();
}
}
View:
#using (Html.BeginForm ("Work", "Admin", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<input id="uploadimage" type="file" />
#ViewBag.Message
<input id="work" type="submit" value="Save Work"/>
}
Thank you.
you're creating a new record in db, but not saving posted files anywhere. try
workpostpath.SaveAs(Server.MapPath("~/folder/file.extension"));
Alsou you could retrieve the posted files from request
HttpPostedFileBase file = Request.Files[0];
Good afternoon, I have an asp.net project and I would like that through an asp.net c # form a patient can download a certificate from a path or folder through their identification number or code, the folder it contains contains pdf and are organized by ID number
Thank you
Due to your vague description, I am not sure if you are an mvc project
or a core project.
The following is a case of downloading pdf in each project, please refer to:
In mvc:
public ActionResult DownLoad()
{
return View();
}
[HttpPost]
public ActionResult DownLoad(string id)
{
//PdfFiles is the name of the folder where these pdf files are located
var path = Server.MapPath("~/PdfFiles/pdf" + id + ".pdf");
var memory = new MemoryStream();
using (var stream = new FileStream(path, FileMode.Open))
{
stream.CopyToAsync(memory);
}
memory.Position = 0;
return File(memory, "application/pdf", Path.GetFileName(path));
}
View:
<form method="post" action="DownLoad">
Pdf Id: <input id="Text1" type="text" name="id" />
<input id="Submit1" type="submit" value="submit" />
</form>
Here is the test result:
In Core:
public IActionResult DownLoad()
{
return View();
}
[HttpPost]
public async Task<IActionResult> DownLoad(string id)
{
//here i put the PdfFiles folder in the wwwroot folder
var path = Path.Combine(
Directory.GetCurrentDirectory(),
"wwwroot", "PdfFiles/pdf" + id + ".pdf");
var memory = new MemoryStream();
using (var stream = new FileStream(path, FileMode.Open))
{
await stream.CopyToAsync(memory);
}
memory.Position = 0;
return File(memory, "application/pdf", Path.GetFileName(path));
}
View:
<form asp-action="DownLoad" method="post">
Pdf Id: <input id="Text1" type="text" name="id"/>
<input id="Submit1" type="submit" value="submit" />
</form>
Here is the test result:
I can upload and download the uploaded files, but I want that users to be able to see only their files. (user1 to see only his data, not also user2's data) How could I do it? Any idea could help. Thanks!
This is my controller, I know that between admin, user, editor I can restrict the access with Authorize, but this wouldn't help me restricting the access between user_id's.
(need to mention that privacy is a very important aspect of my project)
public class FileUploadController : Controller
{
// GET: FileUpload
public ActionResult Index()
{
var items = GetFiles();
return View(items);
}
// POST: FileUpload
[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
if(file != null && file.ContentLength > 0 )
try
{
string path = Path.Combine(Server.MapPath("~/Files"),
Path.GetFileName(file.FileName));
file.SaveAs(path);
ViewBag.Message = "File uploaded successfully";
}
catch(Exception ex)
{
ViewBag.Message = "ERROR:" + ex.Message.ToString();
}
else
{
ViewBag.Message = "You have not specified a file.";
}
var items = GetFiles();
return View(items);
}
public FileResult Download(string downloadedfile)
{
var FileVirtualPath = "~/Files/" + downloadedfile;
return File(FileVirtualPath, "application/force-download", Path.GetFileName(FileVirtualPath));
}
private List <string> GetFiles()
{
var dir = new System.IO.DirectoryInfo(Server.MapPath("~/Files"));
System.IO.FileInfo[] fileNames = dir.GetFiles("*.*");
List<string> items = new List<string>();
foreach (var file in fileNames)
{
items.Add(file.Name);
}
return items;
}
}
This is the view:
<h2> File Upload </h2>
#model List<string>
#using (Html.BeginForm("Index", "FileUpload", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
<label for="file"> Upload </label>
<input type="file" name="file" id="file" />
<br /><br />
<input type="submit" value="Upload" />
<br /><br />
#ViewBag.Message
<br/>
<h2>Documents list</h2>
<table style="width:100%">
<tr>
<th> File Name </th>
<th> Link </th>
</tr>
#for (var i = 0; i <= (Model.Count)-1 ; i++)
{
<tr>
<td>#Model[i].ToString() </td>
<td>#Html.ActionLink("Download", "Download", new { downloadedfile = Model[i].ToString() }) </td>
</tr>
}
</table>
}
<style>
table, th, td {
border: 1px solid white;
}
</style>
You can separate to folder, create a folder with the id of the user, and put the data in user folder.
When you gonna list, only show the folder of the user
Please can someone advise as I have been going round in circles with this. I have a view model which contains a list of my entity:
public List<Employee> EmployeeList{ get; set; }
This is being populated like so:
var list = _context.Employees.Include(x => x.Office).Where(x => x.EmployeeID== id).ToList();
var model = new EmployeeViewModel()
{
EmployeeList= list
};
The view contains:
#model MyProject.Models.EmployeeViewModel
#{
ViewData["Title"] = "Form";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#foreach (var item in Model.EmployeeList)
{
#Html.HiddenFor(modelItem => item.EmployeeID)
#Html.EditorFor(modelItem => item.Name)
}
#using (Html.BeginForm("MyForm", "Employees", FormMethod.Post))
{
<button type="submit" class="btn btn-info" name="SubmitAction" value="Submit">Update</button>
}
I can see all the results but when I change a value on any rows editor from the view no changes are picked up in my controller:
switch (submitAction)
{
case "Submit":
{
foreach (var Response in model.EmployeeList)
{
Console.WriteLine(Response);
}
return View(model);
}
}
Please can anyone point me in the right direction?
Many thanks
Move foreach code to #using (Html.BeginForm) inside
EDITED
Index.cshtml
<form method="post" asp-controller="Employee" asp-action="Index">
#foreach (var item in Model.EmployeeList)
{
<input type="hidden" asp-for="item.EmployeeID" />
<input type="text" asp-for="item.Name" />
}
<button type="submit" class="btn btn-info" name="SubmitAction" value="Submit">Update</button>
</form>
EmployeeController.cs
[HttpPost]
public IActionResult Index(Employee emp)
{
return View();
}
EDITED 05 Feb 2020
Change foreach to for loop.
<form method="post" asp-action="Index">
#{
for (int i = 0; i <= Model.Count() - 1; i++)
{
<input type="hidden" asp-for="#Model[i].Id" />
<input type="text" asp-for="#Model[i].Name" />
<input type="text" asp-for="#Model[i].EmailAddress" />
<br /><br />
}
}
<button>Save</button>
</form>
Input email address.
In your case, use #Model.EmployeeList[i].EmployeeID in view. and use Employee parameter in your controller.
Client side code:
<form action="api/MyAPI" method="post" enctype="multipart/form-data">
<label for="somefile">File</label> <input name="somefile" type="file" />
<input type="submit" value="Submit" />
</form>
And how to process upload file with mvc web-api,have some sample code?
HTML Code:
<form action="api/MyAPI" method="post" enctype="multipart/form-data">
<label for="somefile">File</label>
<input name="somefile" type="file" />
<input type="submit" value="Submit" />
</form>
Controller
// POST api/MyAPI
public HttpResponseMessage Post()
{
HttpResponseMessage result = null;
var httpRequest = HttpContext.Current.Request;
if (httpRequest.Files.AllKeys[0] == "image")
{
if (httpRequest.Files.Count > 0)
{
var docfiles = new List<string>();
foreach (string file in httpRequest.Files)
{
var postedFile = httpRequest.Files[file];
var filePath = HttpContext.Current.Server.MapPath("~/Images/" + postedFile.FileName);
postedFile.SaveAs(filePath);
docfiles.Add(filePath);
}
result = Request.CreateResponse(HttpStatusCode.Created, docfiles);
}
}
else
{
result = Request.CreateResponse(HttpStatusCode.BadRequest);
}
return result;
}
try below link
this link use for me hopefully it will work you
http://www.asp.net/web-api/overview/advanced/sending-html-form-data,-part-2
You can use ApiMultipartFormFormmatter to upload file to web api 2.
By using this library, you can define a view model to get parameters submitted from client-side. Such as:
public class UploadFileViewModel
{
public HttpFile Somefile{get;set;}
}
And use it in your Api controller like this:
public IHttpActionResult Upload(UploadFileViewModel info)
{
if (info == null)
{
info = new UploadFileViewModel();
Validate(info);
}
if (!ModelState.IsValid)
return BadRequest(ModelState);
return Ok();
}
Nested objects can be parsed by this library.