you experts probably knowing the easyiest ways to open/find a file from asp.net mvc application.
could you tell me please how to do that, if i want for example to find and upload a photo from my PC.
Thanks and take care,
Ragims
This article may help you.
The article will show how to upload a
file from client to server location in
ASP.Net MVC application in 5 easy
steps.
Two samples:
example one
example two with unit testing
Just a simple HTML file input in your view will suffice:
<input type="file" name="MyFile" id="MyFile" />
Then accept the file in your controller action:
public ActionResult Upload(HttpPostedFileBase myFile)
{
// save or process file here...
return View();
}
Also, remember to set <form enctype="multipart/form-data"> in your form.
Related
For example, I need only documents from a folder on the server drive X:\Docs for an online web application. Is there a way that a button on the website will open X:\Docs by default? I have tried this to open specific folders with no luck:
[HttpPost]
public ActionResult Index(HttpFileCollection file)
{
var path = System.IO.Path.GetDirectoryName("X:\Docs");
return RedirectToAction("Index");
}
I am new to C# and MVC. Is this achievable?
You can enable directory browsing of that folder and then having the button (or href) to point to the url. You don't event need a controller method for it.
Updated: if the folder is not under your website's root you will need to do some work by yourself. For example
#foreach (string path in Directory.GetFiles("X:\Docs"))
{
<div>
<!--doc link-->
</div>
}
You will need to have read permission for that drive ofc
As Luke pointed out you could alo do this inside your controller and pass it into your View which I also think it might be a better approach since View should be responsible for reading and rendering data
This might be a silly question but I got confuse on the use of FileStream.
At first I thought FileStream is just an System.IO implementation for reading and saving files but there is also FILESTREAM for MSSQL or Database Storage.
https://msdn.microsoft.com/en-us/library/bb933993%28v=sql.100%29.aspx
My problem here is I would like to implement FILESTREAM on my application since I am just going to store profilepictures but what I dont get is the implementation part.
There are no examples or mention on how to use it in Entity Framework like what Filetype to be use or do I need to install a nuget. If I search for implementation of FileStream what I get is System.IO which does not have any reference for saving in database since it is use for file system
I am so confused. Please help.
It looks like that SQL Server FileStream is an over engineering solution for just keeping users avatars on oyour server. You can easily store the avatars on your server as files in some particular folder with having a corresponding record in your avatars reference table that keep the file path or store the avatar as a VARBINARY field in an avatars table.
Storing avatars as files seems to me a more straight forward solution because later on you can add an url of the file in some <img/> in purpose to display the avatar.
As for the rest I would suggest the following:
1) In your MVC view please reffer a model like that
public class AvatarModel
{
public int UserId { get; set; }
public HttpPostedFileBase AvatarFile { get; set; }
}
2) Start your Avatar View with the following statement
using (
Html.BeginForm("Avatar", "UserManagement", FormMethod.Post, FormMethod.Post, new { enctype = "multipart/form-data" } )
)
3) In the View define the inputs and submit button
<input type="hidden" id="UserId" value="#Model.UserId" />
<input type="file" id="AvatarFile" />
<button type="submit"/>
4) In your UserManagement controller implement the following method
[HttpPost]
[ActionName("Avatar")]
public ActionResult AvatarPost(AvatarModel model)
{
...
}
5) in the body of the method you will acess your file over the model argument
model.AvatarFile. The object model.AvatarFile gives you two possibilities either save as a file https://msdn.microsoft.com/en-us/library/system.web.httppostedfilebase.saveas(v=vs.110).aspx or you can read the file as a stream https://msdn.microsoft.com/en-us/library/system.web.httppostedfilebase.inputstream(v=vs.110).aspx convert it to a byte[] and then assign the byte array to a particular model of your entityt framework model.
Please keep in mind that by uploading the file you should keep the POST message <=64 Kbytes. In other case you will have customize your application config and the config of IIS on your server.
But 64 Kbytes should be enought for a avatat isn't it?
I'm getting the error
Server Error in '/' Application.
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /ClientEdit/ClientEdit/1104
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.272
when I add HttpPost attribute to a controller. I've looked into this and corrected my code with posted(no pun intended) answers but nothing I've tried works. Here's my controller header:
[HttpPost]
public ActionResult ClientEdit(int id,FormCollection formCollection)
I added HttpPost so I can populate my FormCollection object. As with other SO posts, this causes the error. Removing it solves the issue but my FormCollection doesn't populate any key/value pairs.
My view has its form tag's method set to POST which solved other dev's issues but it doesn't solve mine. I tried adding 'name=' properties to my textbox controls as well as 'id=' but that doesn't work either.
<body>
<form method="post" action="1104" id="form1">
I don't know what else to try.
You need to provide you view that renders the <form> as well. The action on what you show as your HTML looks wrong to me. I would think it would be something like action="/Controller/ClientEdit".
you have given wrong value in the attribute action="1104".
Either you can specify proper route in action attribute or leave it if the route is same as of get.
This should work if GET and POST route are same
<form method="post" id="form1">
.....
</form>
use this:
#using(Html.BeginForm()){
<!--Your form field-->
}
Basically what is happening is that your action attribute is just pointing to the Id you have and not the url to post to.
You can do it manually like this:
<form action="ClientEdit/ClientEdit/1104>
<!--form fields-->
</form>
Yes, you are all correct. I was passing a userid as the action. This was legacy code that 'worked' for another feature but doesn't conform to the MVC pattern. I did some other research (as I'm not too familiar with MVC either) and started again from scratch using MVC as it should be. Thanks everyone.
I would like to create a jpeg on the fly given some data from a database. The data is an array containing values which should be translated into a colour.
A asp.net mvc controller method should return a jpeg on the fly given one parameter.
This should be fairly straight forward. Could someone please point me to some existing code?
Thanks.
Here are a couple of possible options that may help you get started:
I think you will porbably need an handler and then call the handler from your controller.
SO POst
Bob Cravens post
Scott Hansleman's post
If you want this in pure mvc you can do this
Extending MVC: Returning an Image from a Controller Action
Another way is to create a HttpHandler that does that for you
HTTP Handlers for Images in ASP.NET
hope this helps
There is a tutorial on msdn on How to: Encode and Decode a JPEG Image.
Doing that in MVC3 is pretty similar, you just need a action in your controller like this:
public class YourController : Controller
{
[HttpGet]
public ImageResult GetImage(int whatever)
{
stream imageStream = yourJpgFactory.GetImage(whatever)
return (imageStream)
}
}
and in your view
<img src="YourController/GetImage?whatever=42" />
The controller is:
public class HomeController : Controller
{
public ActionResult LogOn()
{
return View();
}
[HttpPost]
public ActionResult LogOn(string captcha)
{
if (captcha == HttpContext.Session["captcha"].ToString())
return Content("ok");
else
return Content("failed");
}
public CaptchaImageResult ShowCaptchaImage()
{
return new CaptchaImageResult();
}
}
The view is:
<%using (Html.BeginForm())
{ %>
<p><img src="/Home/ShowCaptchaImage" /></p>
<p>Please enter the string as shown above:</p>
<p><%= Html.TextBox("captcha")%></p>
<p><input type="submit" value="Submit" /></p>
<% } %>
Everything goes well, the captcha image is rendered (CaptchaImageResult writes a jpg in the response stream). But if i use the razor view engine there is no captcha image rendered.
How to fix it?
And one more thing: is it a good way to display captcha?
Later edit: <img src=#Href("../../Home/ShowCaptchaImage") /> works fine.
The problem wasn't because razor it was because in the first example i was using Visual Studio Development server and in the second one i was using IIS
<img src="/Home/ShowCaptchaImage" />
This causes the browser to request /Home/ShowCaptchaImage from the root of the HTTP origin (scheme+domain+port) on which you host the application. You need to map the URL to reflect things like any virtual folders in which the app is hosted. If I'm not wrong and this is the problem you are facing, take a look at ResolveUrl/ResolveClientUrl equivalents for Asp.Net Razor? (I haven't tested it, but it looks good).
Also, you could diagnose the problem easily using Firebug or an equivalent tool in another browser - take a look at the requests which are made and you will see what the browser actually requests.