Using WebImage in asp.net core razor mvc - c#

I'm following this sample for working with WebImage. However I'm using asp-net core mvc in vs code.
Since there is no System.Web.Helpers where should I reference WebImage from? I tried searching and there are no explanation in aspnet mvc github wiki.

If you are looking to replace WebImage with a more suitable alternative for asp.net core, then IFormFile is your friend.
You can bind directly to an IFormFile if the parameter name matches the name of your form input field. Or, you can use the below. (Note the change from Request.Files to Request.Form.Files when moving from .net framework to core)
IFormFile inputFile = Request.Form.Files["uploadInputFieldName"];
Instead of the ContentLength property, you may find you need to reference Length instead.
When it comes to saving the file to the local file system (if that is what you are after), then swap out the SaveAs method call for this:
using (var stream = new FileStream(filePathWithSecureName, FileMode.Create))
{
await inputFile.CopyToAsync(stream);
}
More information on file uploads in core, including security considerations, this page is worth a read: https://learn.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads?view=aspnetcore-3.1

to upload webimage
<input type="file" name="updoc" id="upoc" class="form-control" />
and retrieve in controller by
in Controller
HttpPostedFileBase casteCertificate = Request.Files["updoc"];
Add multipart on your html begin form to retrive stream data from view
#using (Html.BeginForm("controller", "action", FormMethod.Post, new { enctype = "multipart/form-data", name = "myForm", id = "myForm" }))
Passing image to View
ViewBag.pic = urlofwebimage;
in view
<img id="Userpic" class="pull-right" style="margin-bottom: 7px" width="180" height="100" src="#ViewBag.pic" />
else u can also do model binding of Image Url

Related

BeginForm messes up controller path value in .NET 6

after migrating my app from .NET Framework 4.8 to .NET6, Html.BeginForm has started to change the slash into "%2F" in the controller path, which causes problems because then they become unreachable.
Basically, this:
<form action="/Admin/Report/DownloadReport" enctype="multipart/form-data" method="post">
Becomes this:
<form action="/Admin%2FReport/DownloadReport" enctype="multipart/form-data" method="post">
Example of code where it happens:
<div class="form-container">
#using (Html.BeginForm("DownloadReport", "Admin/Report", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.Hidden("requestReportName", "PageReport");
<span class="epi-cmsButton">
<input class="epi-cmsButton-text epi-cmsButton-tools epi-cmsButton-Export" type="submit" name="btnSubmitDownloadPageReport" id="btnSubmitDownloadPageReport" value="Download Report" />
</span>}
</div>
What can be the cause of that strange behavior? I have not found any information that Html.Beginform has became obsolete in .NET6.
Edit:
My route mapping:
endpoints.MapControllerRoute(
name: "Admin",
pattern: "Admin/{controller}/{action=Index}");
ASP.NET MVC
If you are working with the Built-In Controller Factory using controller name in format Admin/Report actually does not correct. When the built-in controller factory looking for a controller it uses controller name and looking for Your_Controller_NameController class in YourApp.Controllers.* namespaces.
It is possible to map the specific URL route by defining different namespaces using the namespaces parameter of the MapRoute() method in the ASP.NET MVC.
Try to fix the controller name in the #using (Html.BeginForm("DownloadReport", "Admin/Report", FormMethod.Post, new { enctype = "multipart/form-data" })) to Report. I suppose your application will find the DownloadReport action method without a problem.
See RouteCollectionExtensions.MapRoute Method
ASP.NET Core
I suppose after fixed the controller name in the Html.BeginForm("DownloadReport", "Admin/Report"...) to "Report" your application migration will work correct.
If you will have routing problems provide more information or see the following post: Restrict route to controller namespace in ASP.NET Core

File Upload with AngularJS and ASP.NET MVC

I am new to ASP.NET MVC and AngularJS, How can I Upload file (Image/PDF/Doc) to server Folder By AngularJS Controller with ASP.NET MVC Controller
you can use the angular-file-upload
first install it:
bower install bower install angular-file-upload
then add it as dependency in your app.
angular.module('your-app-name', ['angularFileUpload']);
In your controller, inject the FileUploader service:
angular.module('your-app-name').controller('ctrlName',
['$scope','FileUploader', function($scope, FileUploader) {
$scope.uploader = new FileUploader({
url: 'server_url_here'
//you can add other configuration here like xsrf headers
});
}]);
Then in your html:
Multiple
<input type="file" nv-file-select="" uploader="uploader" multiple /><br/>
Single
<input type="file" nv-file-select="" uploader="uploader" />
You can find a detailed explanation here:
https://github.com/nervgh/angular-file-upload
An example:
https://github.com/nervgh/angular-file-upload/tree/master/examples/simple

How to pass anti forgery token to react via asp.net mvc?

I call my jsx file via the cshtml like so:
#model viewmodels
#Html.React("CreateStuff", new {
options = Model.KeyValues})
My jsx file contains a form which I'd like to POST back to my controller. However, the controller has a ValidateAntiForgeryToken attribute. How can I pass in the token from mvc land to react??
You should to include in your view this row:
#Html.AntiForgeryToken()

How to use FILESTREAM in MVC 5 and EF6

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?

Mvc Release Candidate "File" ActionResult

K... I'm doing something obviously wrong. I have a simple page with a file input control on and a submit button. I'm trying out the new "File" ActionResult that was released with the Mvc RC...
All, I want to happen is when the submit button is clicked the selected file is uploaded to the database. This all works fine...
Then, after the page refreshes I want a image to display the resulting image that was uploaded. The issue, is that the image is not rendering... I get the broken image...
This is the portion that is getting the file and sending it back to the view...
var a = Helper.Service.GetAttachmentById(id, MembershipProvider.SecurityTicket);
if (a == null)
{
return View(new ImagePlaceHolderViewData(new { Id = id }));
}
return View(new ImagePlaceHolderViewData(new { Id = a.Id, Image = a, FileContent = File(a.Data, a.ContentType) }));
Then in the view I have a image tag like so...
<img src="<%=Model.FileContent.FileContents %>" />
I have also tried...
<img src="<%=Model.FileContent%>" />
Thoughts..??
FileResult returns the ASCII or binary contents of the file. When you say do the following:
<img src="<%=Model.FileContent.FileContents %>" />
You are attempting to push the binary image data into the src attribute. That will never work, because the src must a URL or a path to an image.
There are several ways of doing what you want, and the most correct solution in this case, would be to create a new controller that returns the binary data like you are attempting, and then you set the src attribute to be the path to correct action on your new controller. E.g:
<img src="/image/result/12345" />
This points to the following (really simple and incomplete) example controller:
public class ImageController : Controller
{
public ActionResult Result(int resultID)
{
// Do stuff here...
return File(..);
}
}
Note that the name I chose for the action is most likely not any good, but it serves its purpose as an example. Hope this was helpful.
I think it's pretty simple: the src attribute of your img tag requires an URL. What you're doing here is just putting the FileStream object in there (which implicitly calls the ToString method on that object). Your resulting html is probably something like this:
<img src="FileStream#1" />
Did you check your html source?
What you probably should do is provide a method which returns the data, and pass the route to that to your view. Your resulting html 'should' then look something like this:
<img src="/Images/View/1" />
So, steps you have to do are:
Create a method on your controller that returns a FileContentResult
Pass your image ID to your view
Use Url.RouteUrl to generate an url which you can put in your img tag, which points to the method returning your image data.
There's also another solution:
<img src="data:image/gif;base64,<%=Convert.ToBase64(Model.FileContent)%>"/>
which works in some browsers, and doesn't in some browsers(IE! of course). But the stable solution is what Thomas J mentioned.

Categories