Select folder in ASP.NET MVC application to upload files - asp.net-mvc

If I want upload a file it's simply:
Razor
#Html.TextBoxFor(m => m.File, new { type = "file" })
or
Html
<input type="file">
But, If I want select a folder to upload all files than contains, is it possible?
Something like:
Razor
#Html.TextBoxFor(m => m.Folder, new { type = "folder" })
Showing a "select folder dialog".

You can't do that when using #Html.TextBoxFor. There may be another way to upload a folder, but I don't know of it.
However, you can change the file upload dialog to upload multiple files at once, which is essentially the same thing. Here is a tutorial showing how.
Essentially, you need to add the following attribute to your file upload input:
#Html.TextBoxFor(m => m.File, new { type = "file", #multiple = "multiple" })
You also need to add the multpart/form-data attribute to your Razor code to generate the form. Here is an example from that tutorial:
#using (Html.BeginForm("UploadFiles", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
At this point, you can select multiple files to upload. You can easily open the folder, hit CTRL+A to select all, then hit upload to upload the entire folder at once.
Please note that you'll need to modify the controller action to accept multiple files at once.
EDIT: Here is an example on how to handle this in your controller action, from the previously mentioned tutorial. Note that your parameter is an array of HttpPostedFileBase objects, each one representing a file you upload. Then, you iterate through each and save it.
[HttpPost]
public ActionResult UploadFiles(HttpPostedFileBase[] files)
{
//Ensure model state is valid
if (ModelState.IsValid)
{ //iterating through multiple file collection
foreach (HttpPostedFileBase file in files)
{
//Checking file is available to save.
if (file != null)
{
var InputFileName = Path.GetFileName(file.FileName);
var ServerSavePath = Path.Combine(Server.MapPath("~/UploadedFiles/") + InputFileName);
//Save file to server folder
file.SaveAs(ServerSavePath);
}
}
}
return View();
}

Related

Get full path from view in MVC .net

Im trying to upload a picture in a MVC app build on .net
I made a button :
#Html.EditorFor(model => model.Imagen,
new { htmlAttributes = new{ #class = "input", #type="file" } })
But it only gets the name of the picture. I read thats because of security reasons, so what is the simplest way of get the full path of my picture?
I can use anything (.net framework)
The uploaded file doesn't have a path until you save it somewhere. Your Action should receive an HttpPostedFileBase object from the post which you can use to do this.
A simple example:
[HttpPost]
public JsonResult Upload(HttpPostedFileBase upload)
{
var filePath = System.IO.Path.Combine(#"C:\uploads\", upload.FileName);
upload.SaveAs(filePath);
}

Provider hosted asp.net mvc app upload file

I am trying to create a simple post in which I am also attaching an image using Provider Hosted App on Sharepoint online, and I am not able to get SPHostUrl at Controller in HttpContext.Request, I mean SPHostUrl is missing in HttpContext.Request.
[HttpPost]
public ActionResult Contact(SimplePostModel model,HttpPostedFileBase file)
{}
View
#using (Html.BeginForm("Contact","Home",null,FormMethod.Post,new { enctype= "multipart/form-data"}))
The question is if I am sending this part new { enctype= "multipart/form-data"} in the above mentioned statement of View, I am not able to get SPHostUrl parameter in HttpContext.Request.
If I am not sending the html attributes then I am able to get SPHostUrl parameter in HttpContext.Request. and without html attributes I am also not able to upload a file.
Thanks in Advance for your help.
I have solved the issue,by changing some piece of code on in the Razor View.
#using (Html.BeginForm("Contact","Home",null,FormMethod.Post,new { enctype= "multipart/form-data"}))
Instead of null for object route values I send the spHosturl like below.
#using (Html.BeginForm("Contact","Home",new { SPHostUrl = spUrl },FormMethod.Post,new { enctype = "multipart/form-data" }))
the spUrl value comes like below
#{
var spUrl = Request.QueryString["SPHostUrl"];
}
I hope this will help for new sharepoint online developers

Can i download a pdf file saved in media in Umbraco

I need to set create a page on which i have button and on clicking, it should redirect to a registration page and then download a pdf file. so i created a document type in Umbraco which have a file Upload field and i uploaded one file through it. On its template i have added a macro which have a partial view for the registration page. After completing registration, this pdf file should download automatically.
My problem is, the file i uploaded is not showing in the Media library. but the Url is as follows: /media/1051/filname.pdf .
am getting this url in controller. but couldn't get the file usinng its id.
[HttpPost]
public HttpResponseMessage DownloadFile([FromBody] DownloadEBookViewModel model)
{
int id = Convert.ToInt32(model.Url.Split('/')[2]);
var media = Umbraco.Media(id).Url;
if (!File.Exists(media))
throw new HttpResponseException(HttpStatusCode.NotFound);
HttpResponseMessage Response = new HttpResponseMessage(HttpStatusCode.OK);
byte[] fileData = File.ReadAllBytes(media);
if (fileData == null)
throw new HttpResponseException(HttpStatusCode.NotFound);
Response.Content = new ByteArrayContent(fileData);
Response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
return Response;
}
Someone please help. thank you
When working with the Umbraco helper in code behind, I would advise to use the typed variants for getting items
var media = Umbraco.TypedMedia(id).Url;
This will give you a strongly typed model with intellisense
To get the physical file from the media object you'll probably want to call
byte[] fileData = File.ReadAllBytes(media.getPropertyValue("umbracoFile"));
instead of:
byte[] fileData = File.ReadAllBytes(media);
(code is untested)

Error when Uploading image in ASP.NET MVC 3.0

On the local machine the code below works fine, but when hosted on remote server it doesn't seem to find the image file. I created the Image folder and gave it read/ write permissions as well
// --------------------------------------------
Error
Server Error in '/' Application.
Could not find file 'IdImage.jpg'.
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.
Exception Details: System.IO.FileNotFoundException: Could not find file 'IdImage.jpg'.
Code is as below
// ---------------------------------------------
[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Images/Photo"), fileName);
file.SaveAs(path);
}
return RedirectToAction("Index");
}
This looks very much like a permission problem. You said that you have created the Images folder and gave it read/write permission, but from what I can see in your code you are attempting to store the image inside a subfolder called Photo. So make sure you have created this folder as well and given read/write permissions to it as well. Also make sure that you are giving those permissions to the correct account - the one that's configured in IIS to run the application pool in which your application is hosted.
I use this code
[HttpPost]
public ActionResult Upload(System.Web.HttpPostedFileBase file)
{
string filename = Server.MapPath("~/files/somename");
file.SaveAs(filename);
return RedirectToAction("Index");
}
in view
#{
ViewBag.Title = "Upload";
}
<h2>
Upload</h2>
#using (Html.BeginForm(actionName: "Upload", controllerName: "User",
method: FormMethod.Post,
htmlAttributes: new { enctype = "multipart/form-data" }))
{
<text>Upload a photo:</text> <input type="file" name="photo" />
<input type="submit" value="Upload" />
}

Deleting an uploaded file from the server in ASP.NET MVC3

I am trying to upload files to a folder from the admin side like a CMS.
The front-end will display links to download the file.
On the admin end, I would like to not only delete the reference to but also remove the actual file from the server.
Here is the part of my controller that saves the uploaded file:
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
file.SaveAs(path);
ViewBag.fileName = fileName.ToString();
return RedirectToAction("Create", new {fileName = fileName });
}
return RedirectToAction("Index");
}
In the Create view, the admin is then allowed to enter other details about the document and that is stored on a table along with the fileName.
Now I need to be able to link to that document name like document.pdf. Am I even able to link to an uploads folder under App_Data folder?
Also, how do I remove the file and not just the table row on doing delete?
Create a separate controller to handle the downloading of the file. It also prevents your users to hotlink directly to the files.
public ActionResult GetDocument(String pathName)
{
try
{
Byte[] buffer = DownloadMyFileFromSomeWhere(pathName);
FileContentResult result = new FileContentResult(buffer, "PDF"); // or whatever file ext
// these next two lines are optional
String[] folders = pathName.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);
result.FileDownloadName = folders[folders.Length - 1];
return result;
}
catch (Exception ex)
{
// log the error or something
}
return new HttpNotFoundResult();
}
Where DownloadMyFileFromSomeWhere(string) should be able to retrieve the byte-array file from some storage like a blob or even the local server. It can look something like:
private Byte[] DownloadMyFileFromSomeWhere(string pathname)
{
Byte[] file = System.IO.File.ReadAllBytes(Server.MapPath(pathname));
return file;
}
For the Admin side, you can do the same approach: Write a separate controller to delete the file and its entry in the database.
Some notes:
If you have rights to save a file somewhere, you should also have the rights to delete it. You can use normal file operations to do this.
IIS should block you from linking to a file under App_Data. You have a couple of options:
Create an action that reads the file from that location and streams it back to the browser
Store in a different location - somewhere that the user will actually have access to.
The benefit of the first option is that you can easily add authentication, etc. to your action to secure access to the files, whereas the second option would require you to add a web.config in the folder with the appropriate roles and access rights. However, on the other hand, you'll have to supply appropriate headers in your action method so the browser knows what to do with the file, rather than letting IIS figure it out for you.

Resources